JAXP – Java API for XML Parsing @ 1

To parse an xml in java, we can make use of the JAXP – Java API for XML Parsing.  The JAXP provides 2 standards which are SAX and DOM respectively. Here is the sample code which parses an xml using the DOM standard.


<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomParser1 {
	public static void main(String[] args) {
		System.out.println("*** Start ***");

		try {
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			Document document = documentBuilder.parse("./sample1.xml");

			Node parentNode = null;
			Node childNode = null;
			NodeList parentNodeList = null;
			NodeList childNodeList = null;

			parentNodeList = document.getElementsByTagName("Person");

			for (int i = 0; i < parentNodeList.getLength(); i++) {
				parentNode = parentNodeList.item(i);
				childNodeList = parentNode.getChildNodes();

				for (int j = 0; j < childNodeList.getLength(); j++) {
					childNode = childNodeList.item(j);
					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
						System.out.println(childNode.getNodeName() + ": " + childNode.getTextContent());
		} catch (Exception e) {

		System.out.println("***  End  ***");

You can find the following text after running.

*** Start ***
Name: Alice
Gender: Female
Age: 23
Name: Bob
Gender: Male
Age: 25
*** End ***

4 thoughts on “JAXP – Java API for XML Parsing @ 1”

Leave a Reply to ykyuen Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.