Java Tutorials
Building Hadoop MapReduce Jobs In Java
Building XML With Java And DOM
Creating Java Servlets With NetBeans
Basic File Manipulation With Java
Introduction To Java

Building XML With Java And DOM


Attributes are key value pairs that can be attached to elements. They are stored inside the tag in the document, ex: text node .

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class DOMAttrDoc {
    public static void main(String args[]) {
        try {
            String[] input = {"John Doe,123-456-7890,123 Fake St,Atlanta,GA,30012", "Bob Smith,123-555-1212,456 Fake St,Atlanta,GA,30012"};
            String[] line = new String[6];

            DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
            DocumentBuilder build = fact.newDocumentBuilder();
            Document doc = build.newDocument();
            Element root = doc.createElement("root");
            Element memberList = doc.createElement("members");
            for (int i = 0; i < input.length; i++) {
                line = input[i].split(",");
                Element member = doc.createElement("member");
                member.setAttribute("name", line[0]);
                member.setAttribute("phone", line[1]);
                member.setAttribute("street", line[2]);
                member.setAttribute("city", line[3]);
                member.setAttribute("state", line[4]);
                member.setAttribute("zip", line[5]);
            TransformerFactory tFact = TransformerFactory.newInstance();
            Transformer trans = tFact.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter writer = new StringWriter();
            StreamResult result = new StreamResult(writer);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);

        } catch (TransformerException ex) {
            System.out.println("Error outputting document");
        } catch (ParserConfigurationException ex) {
            System.out.println("Error building document");

As before initialize the data set and the array to hold the comma split values. Notice the extra fields in the data from the previous example. Setup the DocumentBuilderFactory and DocumentBuilder objects to create the document. Now create the root element and attach it to the document. As before create the root tag with the createElement() method and use appendChild() to attach it to the document. Use the createElement() method to create the members tag that the list will be the parent of the member elements and append it to the root node. The values of the input array will be stored in the XML document as attributes of the member node.

Loop through the values of the array. First split the array value into comma seperated values with split. Next create the member node. Use the setAttribute() method of the member node object to add the values to the node. The setAttribute() method expects the attribute name and value to be passed as parameters. Once all the attributes are added append the member node as a child of the members node.

When the loop completes the TransformerFactory is used to convert the DOM document to a string. Use the TransformerFactory object to create a Transformer object. To build a document that is easier for humans to read use the setOutputProperty() method of the transformer object to set the OutputKeys.INDENT value to yes. This will insert tabs and line feeds into the document.

Build a StringWriter and StreamResult to pass to the transformer to get the XML as a string. Initialize a DOMSource object for the transformer to use to get the XML from the DOM object. The transformer objects transform method is used to convert the DOM object to a string. Use the StringWriters toString method to get the text value of the XML. The last thing to do is catch the possible exceptions that might be thrown. The ParserConfigurationException is thrown by the DocumentBuilder and the TransformerException is thrown by the Transformer object.

Basic XML & DOM <<  1 2
New Content