Building an XML Structure and Parse the XML file

Through this article, let me create a simple XML file and parse it using a DOM Parser. First of all let's create a sample XML file with some elements and attributes.

Build an XML file

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="Projects.xsl"?>
<catalog>
    <model name="s3">
        <network>GSM</network>
        <launch>2012-10-12</launch>
        <os>Android</os>
        <version>4.1</version>
        <cpu>dual-core</cpu>
        <weight>111.5</weight>
        <sim>mini-sim</sim>
    </model>
    <model name="s5">
        <network>GSM</network>
        <launch>2013-10-12</launch>
        <os>Android</os>
        <version>4.4</version>
        <cpu>quard-core</cpu>
        <weight>140.5</weight>
        <sim>micro-sim</sim>
    </model>
</catalog>

The root element of the created XML file is 'catalog'. The other elements appeared in the sample XML are model, network, launch, os, version, cpu, weight and sim. The 'model' element contains an attribute named 'name'

Parse the XML file

There are few ways of parsing an XML file. Some of them are,
  • DOM Parsers
  • SAX Parsers
  • STAX Parsers
In this article  lets use SAX Parser to Parse the XML file.
package com.trainings.source;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

/**
 * @author hasanthi
 *
 */
public class ReadPhoneXML {
 public static void main(String[] args) {
    File file = new File("./resources/phones.xml");
        try {
            DocumentBuilder documentBuilder = DocumentBuilderFactory
                    .newInstance().newDocumentBuilder();
            try {
                Document doc = documentBuilder.parse(file);
                System.out.println("Root element :"
                        + doc.getDocumentElement().getNodeName());

                if (doc.hasChildNodes()) {
                   printNote(doc.getChildNodes());
                }
                 } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param nodeList
     *     xml elements as a NodeList
     */
    private static void printNode(NodeList nodeList) {
        for (int count = 0; count < nodeList.getLength(); count++) {
           Node tempNode = nodeList.item(count);
           // make sure it's element node.
            if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
                       // get node name and value
                System.out.println("\nNode Name =" + tempNode.getNodeName());
                if (tempNode.getChildNodes().getLength() == 1) {
                    System.out.println("Node Value ="
                            + tempNode.getTextContent());
                }
            }
            if (tempNode.hasAttributes()) {
                     // get attributes names and values
                NamedNodeMap nodeMap = tempNode.getAttributes();
                for (int i = 0; i < nodeMap.getLength(); i++) {
                    Node node = nodeMap.item(i);
                    System.out.println("attr name : " + node.getNodeName());
                    System.out.println("attr value : " + node.getNodeValue());
                                }
                        }
            if (tempNode.hasChildNodes()) {
                       // loop again if has child nodes
                printNote(tempNode.getChildNodes());

            }
    }
    }
}
The output of above code snippet is as below.
Now let's consider the important parts of the above code. Inside the main method it prints the root element details while passing the child node list to the printNode method. The printNode method is a recursive function. It prints the child elements of the root node. If the child element has its own child elements then it again invokes the same printNode method and prints its child elements.

Comments

Popular posts from this blog

Applying CORS Filter to wso2 Identity Server

JWKS endpoint of wso2 IS

DCR VS DCRM with WSO2 Identity server