Monday, February 27, 2012

XML - DOM Parser

Java XML DOM parser is the easiest API for parsing XML files.

With this parser, we load the entire XML file into memory. Then extract any element with its name, extract its child elements, etc.

Let us see this with an example.

We will parse a XML file which contains a couple of Users - their first and last names.

In your /data folder, create a file users.xml, like this:
 <users>  
<user>
<firstName>Jenny</firstName>
<lastName>Lee</lastName>
</user>
<user>
<firstName>Benny</firstName>
<lastName>Carlson</lastName>
</user>
</users>

Now let us use the Java XML DOM parser to extract both the users from this file.

In your /src/org/confucius folder, create a class UserDOMParser.java, like this:
 package org.confucius;  

import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


public class UserDOMParser {

public static void main(String[] args) {
try {
File usersFile = new File("data/users.xml");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(usersFile);

NodeList users = doc.getElementsByTagName("user");

for (int i = 0; i < users.getLength(); i++) {
Element user = (Element) users.item(i);

String firstName = user.getElementsByTagName("firstName").item(0).getTextContent();
String lastName = user.getElementsByTagName("lastName").item(0).getTextContent();

System.out.println("Got User: " + firstName + " " + lastName);
}

} catch (Exception e) {
e.printStackTrace();
}
}
}

What are we doing here?
We used the DocumentBuilder to read the XML file, then extracted the <user> elements, looped over and printed out the first and last names of each user.

R-click on UserDOMParser.java in your Eclipse Navigator view and select Run As->Java Application.

You will see the users printed to the console.

No comments: