Search code examples
javaxmlapache-commons-digester

Java - Apache commons Digester - write xml


I'm using Apache Commons Digester (with annotations) in order to load an XML file into a Java class. Everything works correctly. Now, I need to update the XML file. I have to change (in Java) the value of a property, and then to write out the new XML file. How could I do? As far as I can see, Digester API is not designed for this purpose.

Edit: reading the answers, I understand that I did not give enough informations. My XML file is a configuration file for a program A, so I really need its content when I launch program A. Then, I have another GUI program B that is able to modify this configuration file, it just takes some input from the user and modifies the relative fields on the XML file.


Solution

  • As you have found, Digester is a read-only tool - it provides a mapping from XML to Java classes, but not the reverse. If you need to read the XML into Java classes and then write it back to XML again, I would suggest either:

    • Keep using Digester for the reading, and use a low-level XML writer class (such as XMLStreamWriter) to write the data back. This is suitable if your data is not that complex, and/or the output XML is a different structure to the input XML.
    • Replace Digester with a full Java to XML mapping library (JAXB, JiBX etc.), which will both read and write the XML for you. This is suitable if your data is more complex, and/or the output XML is the same structure as the input XML.

    Don't know enough about what you are doing to really recommend one of those approaches over the other.

    If you don't actually need the data in Java classes at all and are just trying to transform it, then XSLT as @sharonbn says is also a good solution.