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