Xml XPath Basics, Expressions, keywords in java

  • XPath is a language for finding information in an XML file.
  • XPath provides syntax to define part of an XML document.
  • XPath Expression is a query language to select part of the XML document based on the query String.
  • You can say that XPath is SQL for XML files.
  • XPath is used to navigate through elements and attributes in an XML document.
  • XPath is a powerful expressions language it can be used to parse an xml document and retrieve relevant information.
  • javax.xml.xpath package provides XPath support in Java.

Syntax to create XPathExpression

XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
XPathExpression expression = xpath.compile(XPATH_EXPRESSION_STRING);
Object result = expression.evaluate(Object item, QName returnType);
Following return types are defined in XPathConstants class:

  1. XPathConstants.STRING
  2. XPathConstants.NUMBER
  3. XPathConstants.BOOLEAN
  4. XPathConstants.NODE
  5. XPathConstants.NODESET

XPath Expressions:

XPath uses a path expression to select nodes or list of node from an xml document.

Following list of useful paths and expression that can be used to select any node/nodelist from an xml document.

Sample xml file

<?xml version="1.0"?>
<Employees>
<Employee emplid="1" type="admin">
<firstname>Narayanaswamy</firstname>
<lastname>Ragi</lastname>
<age>30</age>
<email>[email protected]</email>
</Employee>
<Employee emplid="2" type="user">
<firstname>RaviKumar</firstname>
<lastname>Barhal</lastname>
<age>32</age>
<email>[email protected]</email>
</Employee>
</Employees>

Examples

exp 1 : employee
Selects all nodes with the name employee
employees/employee
Selects all employee elements that are children of employees
exp 2 : //employee
Selects all book elements no matter where they are in the document
exp 3 : @
Selects attributes
exp 4 : ..
Selects the parent of the current node
exp 5 : .
Selects the current node
exp 6 : //
Selects nodes in the document from the current node that match the selection no matter where they are
exp 7 : /
Selects from the root node
exp 8 : nodename
Selects all nodes with the name nodename
Predicates expressions 
To find a specific node or a node that contains a specific value using expressions are called Predicates. The Predicates are defined in square brackets [ … ]. Following list of useful Predicates expression.

Examples

exp 1 : //employee[@type=’admin’]
Selects all the employee elements that have an attribute named type with a value of admin
exp 2 : /employees/employee[1]
Selects the first employee element that is the child of the employees element.
exp 3 : /employees/employee[last()]
Selects the last employee element that is the child of the employees element
exp 4 : /employees/employee[last()-1]
Selects the last but one employee element that is the child of the employees element
We will discuss each and every expression with examples in ther blog.

Leave a Reply