Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

xml

sax

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?

like image 820
Roman Avatar asked Oct 23 '25 00:10

Roman


2 Answers

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();
} 
like image 75
Peter Knego Avatar answered Oct 24 '25 15:10

Peter Knego


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.

like image 20
Greg Case Avatar answered Oct 24 '25 15:10

Greg Case



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!