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

I am reading an XML file with a SAX parser (this part can be modified there for this).

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

How can i do this?

+3
source share
2 answers

Afaik, SAX - only a parser. You must select a different library for writing XML.

If you change attributes or change element names and DO NOT change the XML structure, this should be a relatively simple task. Use STaX as an author:

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

Now add 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();
} 
+7
source

, JDOM. SaxBuilder, Document InputStream, Xpath, node/, , , XmlOutputter, .

, ( ), SAX, , , - .

XSLT.

+2

Source: https://habr.com/ru/post/1772005/


All Articles