Use of "|" separator for selecting more than one path
You can execute multiple expressions on an XML file with the use of XPath "|" separator. It allows you more flexibility by allowing you to execute multiple expressions at a time.
In this example we have created an XML file "persons.xml" as in our previous section, which is necessary to execute XPath query on to it. This "persons.xml" contains information related to name, age, gender of different persons.
Here is the full source code for persons.xml file as follows :
persons.xml
<?xml version="1.0" ?> |
Now we have declared a class XPathSeparator and in this class we are parsing the XML file with JAXP. First of all we need to load the document into DOM Document object. We have put that persons.xml file in that current working directory.
DocumentBuilderFactory domFactory = |
Above lines of code parses "persons.xml" file and creates a Document object. Next we have created XPath object with the use of XPathFactory.
XPath xpath = XPathFactory.newInstance().newXPath(); |
When we will execute the following expression then it
will execute both expressions "//person/name/text()" as well as
"//person/age/text()".
Here is the full example code for XPathSeparator.java as follows:
XPathSeparator.java
import org.w3c.dom.*;
|
Output:
To run this example :
- create and save persons.xml file
- create and save XPathSeparator.java
- compile and execute XPathSeparator class and you will get following output on your screen.