tags:

views:

39

answers:

2

I'm reading an XML file with a SAX-parser (this part can be changed it there's a good reason for it).

When I find necessary properties I need to change their values and save the resulting XML-file as a new file.

How can I do that?

+1  A: 

If your document is relatively small, I'd recommend using JDOM. You can instantiate a SaxBuilder to create the Document from an InputStream, then use Xpath to find the node/attributes you want to change, make your modifications, and then use XmlOutputter to write the modified document back out.

On the other hand, if your document is too large to effectively hold in memory (or you'd prefer not to use a 3rd party library), you'll want to stick with your the SAX parser, streaming out the nodes to disk as you read them, making any changes on the way.

You may also want to take a look at XSLT.

gregcase
+1  A: 

Afaik, SAX is parser only. You must choose a different library to write XML.

If you are only changing attributes or changing element names and NOT changing structure of XML, then this should be relatively easy task. Use STaX as a writer:

// Start STaX 
OutputStream out = new FileOutputStream("data.xml");
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter writer = factory.createXMLStreamWriter(out);

Now, extend the SAX DefaultHandler:

startDocument(){
    writer.writeStartDocument("UTF-8", "1.0");
}

public void startElement(String namespaceURI, String localName,
                         String qName, Attributes atts)  {

    writer.writeStartElement(namespaceURI, localName);
    for(int i=0; i<atts.getLength(); i++){
        writer.writeAttribute(atts.getQName(i), atts.getValue(i));
    }
} 

public void endElement(String uri, localName, qName){
    writer.writeEndElement();
} 
Peter Knego
Thanks, I got the idea. I'm not sure that I'll use it (maybe I'll prefer some library instead) but that's what I asked.
Roman