Question

I have an xml template file, some fields are blank and need to be filled by my application. This has to result in an xml string representation of that file which will be given to another routine.

So, let's take this simple xml as example:

<root>
   <name anAttr=""></name>
   <age></age>
</root>

As you can see I'd have to read the xml and, in the parsing process, add some contents to it.

I though about using a sax parser and in the handler I would do something like this:

StringBuilder finalXml = new StringBuilder();

DefaultHandler handler = new DefaultHandler(){

        public void startElement(String uri, String localName,String qName, 
                Attributes attributes) throws SAXException {
                            finalXml.append("<"+qName+">");
                            if(qName.equals("name")){
                                finalXml.append("donald");
                             }

        }

would it be correct/efficient this way? Or is there a better way?

Was it helpful?

Solution

I've used dom4j when i have wanted to parse xml in Java, and it's quite efficient.

OTHER TIPS

If you have a choice of technology then I would suggest using JAXB .

It will unmarshal the XML into Java Object ,here do the modifications to java Object and then Marshal the modified Java Object into new XML File.

It has little bit of learning curve but code will be readable and maintainable.

for Basic tutorial of JAXB please refer to URL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top