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
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.