Parse xml from file using DOM parser

In java there are many ways to parse XML, in this example we will show how to read xml from a file and parse it with the java DOM API. The document object model is an interface that defines a logical structure with XML and java provides an API to access nodes within xml. Java DOM Parser is considered one of the slower parsers so if are dealing with high volume transaction or large xml files consider alternatives.

We learned how to make a get request and called a REST API to pull a data stream from the cloud. We will pull a snippet of xml from the Wimp Weather Station that represents a list of locations while parsing it.

Sample xml

<?xml version="1.0" encoding="UTF-8" ?>
        <long>Boulder, CO, United States</long>
        <country>United States</country>
        <long>Janesville, WI, United States</long>
        <country>United States</country>

Using java dom api

We will first create a new instance of DocumentBuilderFactory which will allow ability to create a DocumentBuilder. Next using java 7 file syntax for reading a file we will create a path and call toFile() to return a file representation of the path. We will pass the file to DocumentBuilder.parse to create a new document. This will load the XML into memory and allow us retrieve, parse and iterate over the nodes. Finally we call getElementsByTagName(*) to return a NodeList which will allow us to iterate over each element and print the tag content.

public void read_xml_file_with_dom_parser()
        throws ParserConfigurationException, SAXException, IOException {

    //Create a DOM Builder Factory
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

    //Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();

    //Use path to get file
    Path xmlFilePath = Paths

    //Parse the XML document
    Document document = builder.parse(xmlFilePath.toFile());

    //Loop over all nodes in XML outputting the content that resides in the tag
    NodeList nodeList = document.getElementsByTagName("*");
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);

        if (node.getNodeType() == Node.ELEMENT_NODE) {
            String content = node.getLastChild().getTextContent().trim();

            switch (node.getNodeName()) {
            case "long":
                System.out.println("Long name:" + content);
            case "city":
                System.out.println("city name:" + content);
            case "state":
                System.out.println("state name:" + content);
            case "country":
                System.out.println("country name:" + content);



Long name:Boulder, CO, United States
city name:Boulder
state name:Colorado
country name:United States
Long name:Janesville, WI, United States
city name:Janesville
state name:Wisconsin
country name:United States