I think this link may be useful for you.
Here you have examples of how to read / parse, modify (add elements) and save (write to the xml file again).
The following samples can be found at: http://www.petefreitag.com/item/445.cfm
Reading:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("/path/to/file.xml");
Modify:
// attributes Node earth = doc.getFirstChild(); NamedNodeMap earthAttributes = earth.getAttributes(); Attr galaxy = doc.createAttribute("galaxy"); galaxy.setValue("milky way"); earthAttributes.setNamedItem(galaxy); // nodes Node canada = doc.createElement("country"); canada.setTextContent("ca"); earth.appendChild(canada);
XML file entry:
Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //initialize StreamResult with File object to save to file StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(doc); transformer.transform(source, result); String xmlString = result.getWriter().toString(); System.out.println(xmlString);
source share