JAXP – Java API for XML Parsing @ 2

Most of the time, the xml contains node attributes other than node values. The following example shows u how to get the node attributes in xml.

sample2.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<People>
	<Person
		Name='Alice'
		hp='Female'
		mp='23'
	/>
	<Person
		Name='Bob'
		hp='Male'
		mp='25'
	/>
</People>

DomParser2.java

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 DomParser2 {
	public static void main(String[] args) {
		System.out.println("*** Start ***");

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

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

			parentNodeList = document.getElementsByTagName("Person");

			for (int i = 0; i < parentNodeList.getLength(); i++) {
				parentNode = parentNodeList.item(i);
				NamedNodeMap attributes = parentNode.getAttributes();

				for (int j = 0; j < attributes.getLength(); j++) {
					childNode = attributes.item(j);
					System.out.println(childNode.getNodeName() + ": " + childNode.getTextContent());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

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

You can get the same result as in JAXP – Java API for XML Parsing @ 1

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

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