Reading and writing simple XML documents using w3c DOM library

Generating a new XML document

1. Obtain a new instance of an XML parser and a new document builder instance

DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();

2. Obtain a new DOM document from the former factory

Document document = builder.newDocument();

3. Generating the XML tree content

3.1. The root tag element (that I called for convenience “my-root”)

Element rootElement = document.createElement("my-root");
document.appendChild(rootElement);

3.2. A child tag element (that I called for convenience “my-child”), setting to it an attribute name “my-attribute” with a value “my-value”

Element documentElement = document.createElement("my-child");
documentElement.setAttribute("my-attribute", "my-value");
rootElement.appendChild(documentElement);

4. Saving the XML tree to a file

XMLSerializer serializer = new XMLSerializer();
serializer.setOutputByteStream(new FileOutputStream(file));
serializer.serialize(document);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s