Share on Google+Share on Google+

Use of @ for attribute in XPath

In the previous section of XPath tutorial we have studied how to show all elements of an XML file.

Use of  @ for attribute in XPath


In the previous section of XPath tutorial we have studied how to show all elements of an XML file. In this section we are describing you the use of @ for attribute in the XPath query. The "@" selects attribute.

In this example we have created an XML file "person.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 :


<?xml version="1.0" ?>
  <person id="1">
 <person id="2">
  <person id="3">

  <!-- more persons... -->

Now we have declared a class XPathAttribute  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 = 

  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("persons.xml");

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();

We want to show all elements with attribute id="3" of the person so we can write this in the XPath query as :

"//person[@id='3']/*" -it will fetch all elements with person id="3" .
Full example code is given as below:

import org.w3c.dom.*;
import javax.xml.xpath.*;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;

public class XPathAttribute{

  public static void main(String[] args
 throws ParserConfigurationException, SAXException, 
  IOException, XPathExpressionException {

  DocumentBuilderFactory domFactory = 
  DocumentBuilder builder = domFactory.newDocumentBuilder();
  Document doc = builder.parse("persons.xml");
  XPath xpath = XPathFactory.newInstance().newXPath();
  XPathExpression expr =
  Object result = expr.evaluate(doc, XPathConstants.NODESET);
  NodeList nodes = (NodeListresult;
  for (int i = 0; i < nodes.getLength(); i++) {

To run this example :

  • create and save persons.xml
  • create and save and
  • compile XPathAttribute and after compilation execute it

output would be like this:


Download Source Code



Posted on: September 29, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Use of @ for attribute in XPath  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image