Parse XML file in JAVA

Parse XML file in JAVA

Parse XML file in JAVA

Most developers developing Enterprise Applications need to know how to Parse XML file in JAVA. These applications may use xml files for data representation, data transfer and messaging.

JAVA currently has good support for XML and this is embedded in the JAVA API (it is not an external API), with the JAVA API you can create, read, write and modify xml files.

What is XML? According to James Duncan Davidson (2000) XML is the Meta language defined by the World Wide Web Consortium (W3C) that can be used to describe a broad range of hierarchical markup languages. It is a set of rules, guidelines, and conventions for describing structured data in a plain text, editable file

XML is universally accepted, an like JAVA it is platform dependent, as such XML can be used to transfer data between two different applications written in different languages e.g. Transferring data between an application written in C++ and one written in JAVA.

There are two ways to parsing XML files using JAVA and they are the DOM (Document Object Model) parser and the JAXP (JAVA API for XML Parsing), the two methods will be briefly explained, but an actual example will be implemented using the DOM parser

JAXP – Java API for XML Parsing

Java provides extensive support for reading XML file, writing XML file and accessing any element from

XML file. All XML parsing related classes and methods are inside JAXP. Though DOM related code comes from org.w3c.dom package. All XML parsers are in javax.xml.parsers package. we will see example of parsing xml files using JAXP API in next section.

Parse XML File in Java using DOM Parser

In this section we will see how to parse xml files or how to read xml file using DOM XML Parser. DOM is quick and easy way to parse xml files in Java and if you are doing it for testing its way to go. Only thing to concern is that XML files which need to be parsed must not be too large. You can also create xml file by using DOM parser and DocumentFactory Class in Java.

Here is xml file Stocks.xml which contains some stocks and there price, quantity we will use this in our xml parsing example in Java.


<?xml version="1.0" encoding="UTF-8"?>
<stocks>
<stock>
<symbol>Citibank</symbol>
<price>100</price>
<quantity>1000</quantity>
</stock>
<stock>
<symbol>Axis bank</symbol>
<price>90</price>
<quantity>2000</quantity>
</stock>
</stocks>

Code Example of Parsing XML File in Java using DOM Parser

Here is a code example of parsing above xml file in Java using DOM parser:

 

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DOMExampleJava {

public static void main(String args[]) {
try {

File stocks = new File(“Stocks.xml”);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();

System.out.println(“root of xml file” + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName(“stock”);
System.out.println(“==========================”);

for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
System.out.println(“Stock Symbol: ” + getValue(“symbol”, element));
System.out.println(“Stock Price: ” + getValue(“price”, element));
System.out.println(“Stock Quantity: ” + getValue(“quantity”, element));
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}

Output:

root of xml file stocks
==========================
Stock Symbol: Citibank
Stock Price: 100
Stock Quantity: 1000
Stock Symbol: Axis bank
Stock Price: 90
Stock Quantity: 2000

That’s all on xml parsing in java for now. We have seen how to read and write xml file in Java and now familiar with both DOM and SAX Parser in java. We will see more on xml on coming days like reading xml elements via xpath and using xml beans etc. let me know if you have any doubt on xml parsing example or in general with xml and Java.

References

James Duncan Davidson (et al) (2000), Java API for XML Parsing, Version 1.0 Final Release [Online] [Accessed: 29/8/2014]