could any one provide an example of extracting all the elements with their attributes and values from an xml file using xpath in java?
Thanks
could any one provide an example of extracting all the elements with their attributes and values from an xml file using xpath in java?
Thanks
I wrote this few years back for my team. Would be helpful.
In XPath, there are seven kinds of nodes: element, attribute, text, name-space, processing-instruction, comment, and document (root) nodes. XML documents are treated as trees of nodes. The root of the tree is called the document node (or root node).
Consider the following Xml document.
<information>
<person id="1">
<name>Tito George</name>
<age>25</age>
<gender>Male</gender>
<dob>
<date>25</date>
<month>october</month>
<year>1983</year>
</dob>
</person>
<person id="2">
<name>Kumar</name>
<age>32</age>
<gender>Male</gender>
<dob>
<date>28</date>
<month>january</month>
<year>1975</year>
</dob>
</person>
<person id="3">
<name>Deepali</name>
<age>25</age>
<gender>Female</gender>
<dob>
<date>17</date>
<month>january</month>
<year>1988</year>
</dob>
</person>
</information>
Getting information from the Document
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
//Getting the instance of DocumentBuilderFactory
domFactory.setNamespaceAware(true);
//true if the parser produced will provide support for XML namespaces;
DocumentBuilder builder = domFactory.newDocumentBuilder();
//Creating document builder
Document doc = builder.parse("C:\\JavaTestFiles\\persons.xml");
XPath xpath = XPathFactory.newInstance().newXPath();
//getting instance of xPath
expr = xpath.compile("//@id");
result = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
The line above in red is the one which is used for compiling xPath expression and //@id is the actual expression . The expression //@id will return and the values of attribute id in the document. ie. out put of the program will be 1 2 and 3. In the below table you can find the various expressions that can be used in this document.
Two important statements in the above code snippet is
Basically: An XML document is a tree-structured (hierarchical) collection of nodes. As with a hierarchical directory structure, it is useful to specify a path that points to a particular node in the hierarchy (hence the name of the specification: XPath).
In fact, much of the notation of directory paths is carried over intact:
Use this XPath expression "//*"
in this way
Document doc = ... // the document on which apply XPath
XPathExpression xp = XPathFactory.newInstance().newXPath().compile("//*");
NodeList elements = (NodeList) xp.evaluate(doc, XPathConstants.NODESET);
It return to you all the elements at any level.