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" ?>
<locations>
<location>
<long>Boulder, CO, United States</long>
<city>Boulder</city>
<state>Colorado</state>
<country>United States</country>
<lat>40.0149856</lat>
<lng>-105.27054559999999</lng>
</location>
<location>
<long>Janesville, WI, United States</long>
<city>Janesville</city>
<state>Wisconsin</state>
<country>United States</country>
<lat>42.682788500000000000</lat>
<lng>-89.018722200000010000</lng>
</location>
</locations>
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.
@Test
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
.get("src/test/resources/com/levelup/java/xml/read-xml-file-dom-parser.xml")
.toAbsolutePath();
//Parse the XML document
Document document = builder.parse(xmlFilePath.toFile());
document.getDocumentElement().normalize();
//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);
break;
case "city":
System.out.println("city name:" + content);
break;
case "state":
System.out.println("state name:" + content);
break;
case "country":
System.out.println("country name:" + content);
break;
}
}
}
}
Output
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