Parsing, Modifying, and outputting XML Documents with Java
I have been doing a lot of XML parsing, and manipulation in java lately because I'm building a super dynamic configuration editor for XMS. Its going to be pretty cool once its done because you can even configure third party modules with it. Anyways I thought I'd post some a simple example of parsing and modifying XML with java:
Suppose you have the following XML document:
<?xml version="1.0" ?> <earth> <country>us</country> </earth>
First to parse it using a DOM parser, you can use the DocumentBuilderFactory to get the default DOM parser for your JVM:
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse("/path/to/file.xml");
Now you have an object representation of the XML file in a DOM Document object.
Adding an attribute
Suppose you wanted to add an attribute to the earth node:
Node earth = doc.getFirstChild(); NamedNodeMap earthAttributes = earth.getAttributes(); Attr galaxy = doc.createAttribute("galaxy"); galaxy.setValue("milky way"); earthAttributes.setNamedItem(galaxy);
Adding a child tag
Now lets suppose you wanted to add a child node:
Node canada = doc.createElement("country"); canada.setTextContent("ca"); earth.appendChild(canada);
Write the XML document to a string or file
Finally you probably want to write the xml document to a string or to a file, this can be done with a Transformer object, which come from the transformer factory:
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);
Like this? Follow me ↯Tweet Follow @pfreitag
Parsing, Modifying, and outputting XML Documents with Java was first published on August 16, 2005.
Want Security Advisories via Email?
Advisory Week is a new weekly email containing security advisories published by major software vendors (Adobe, Apple, Microsoft, etc).