DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Simple Java DOM XML Processing Example

  • submit to reddit
        // Simple Java DOM XML Processing Example
// Source:


import org.w3c.dom.*;

import javax.xml.parsers.*;

import javax.xml.transform.*;
import javax.xml.transform.dom.*;

public class DomXmlExample {

     * Our goal is to create a DOM XML tree and then print the XML.
    public static void main (String args[]) {
        new DomXmlExample();

    public DomXmlExample() {
        try {
            // Creating an empty XML Document

            // We need a Document
            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
            Document doc = docBuilder.newDocument();

            // Creating the XML tree

            // create the root element and add it to the document
            Element root = doc.createElement("root");

            // create a comment and put it in the root element
            Comment comment = doc.createComment("Just a thought");

            // create child element, add an attribute, and add to root
            Element child = doc.createElement("child");
            child.setAttribute("name", "value");

            // add a text element to the child
            Text text = doc.createTextNode("Filler, ... I could have had a foo!");

            // Output the XML

            // set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            // create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();

            // print xml
            System.out.println("Here's the xml:\n\n" + xmlString);

        } catch (Exception e) {


Carla Brian replied on Mon, 2012/07/16 - 5:04pm

Good thing I saw this post. This is exactly what I need. I need to learn more about xml processing using Java. I better research for more tutorials and etc. - Mercy Ministries

faomsm faeosm replied on Thu, 2009/08/20 - 1:51pm

yes this is the best example for java xml code.I would like to know whether any use is there with java xml in creating game site sir? Thank you.Regards , Magic the Gathering

gfdgf fgds replied on Tue, 2009/06/16 - 4:44am

I am little bit weak in java concepts and I need your help in knowing well about this site. free online games