Roman
Roman

Reputation: 66156

How to change values of some elements and attributes in an XML file [Java]?

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?

Upvotes: 4

Views: 6311

Answers (2)

Peter Knego
Peter Knego

Reputation: 80340

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();
} 

Upvotes: 7

Greg Case
Greg Case

Reputation: 3240

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.

Upvotes: 2

Related Questions