Clicky

ChrisEllsworth.com

The online home of Christopher Chess Ellsworth
Welcome to ChrisEllsworth.com Sign in | Join | Help
in Search

Chris's Development Blog

Tutorials and thoughts on software development.

Java XML Parsing with DOM

This example will get you started in the exciting world of XML parsing with Java and DOM!

Test.xml

<root>
    <foo>someFoo</foo>
    <child>
        <subchild name="chris">valueOne</subchild>
    </child>
    <child>
        <subchild name="barry">valueTwo</subchild>
    </child>
</root>

 

XMLParsingExample.java

import java.io.*;

import javax.xml.parsers.*;
import org.w3c.dom.*;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.dom.DOMSource;
 
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;

public class XMLParsingExample {
    public static void main(String [] args) {
        System.out.println("Starting...");

        try {
            String fileName = "test.xml";

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

            // Could use an InputStream instead of a File
            Document xmlDocument = builder.parse(new File(fileName));
            Element rootNode = xmlDocument.getDocumentElement();

            NodeList nodeList = rootNode.getElementsByTagName("child");
            for(int i=0;i < nodeList.getLength();i++) {
                Node node = nodeList.item(i);
                System.out.println(node);
            }
        }
        catch(Exception e) { e.printStackTrace(); }
    }
}

Published Thursday, January 13, 2005 7:59 PM by Christopher Chess Ellsworth
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit

Locations of Visitors

Locations of visitors to this page
©2007 Christopher Chess Ellsworth