Search code examples
javaxmldomsax

Java: read input xml and write output xml with some updated attribute values


I have to read a big xml file (A.xml) and create a new xml file (B.xml) with the same content as A.xml except for some attribute values that need to be updated in B.xml. For example if A.xml is:

<?xml version="1.0" encoding="utf-8"?>
<one>
    <!-- comment -->
    <a att="hello" />
</one>
<two />

I want B.xml to contain:

<?xml version="1.0" encoding="utf-8"?>
<one>
    <!-- comment -->
    <a att="UPDATED" />
</one>
<two />

I was looking at one solution that uses SAX for parsing and a PrintWriter for writing, but it looks quite low level and I don't know if it is possible to copy comments and keep this type of close tags: />. I'd prefer a streaming parser rather than loading the whole document in memory but I'm open to suggestions.


Solution

  • For a streaming solution you can use a javax.xml.stream.XMLStreamReader or XMLEventReader to read the XML document, update any parts that you want to change, and pipe the data/events from the reader into a javax.xml.stream.XMLStreamWriter or XMLEventWriter.