[xml] Getting attribute using XPath

Given an XML structure like so:

<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book>
  <title lang="eng">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="eng">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>

How could I get the value of lang (where lang is eng in book title), for the first element?

This question is related to xml xpath

The answer is


The standard formula to extract the values of attribute using XPath is

elementXPath/@attributeName

So here is the xpath to fetch the lang value of first attribute-

//title[text()='Harry Potter']/@lang

PS: indexes are never suggested to use in XPath as they can change if one more title tag comes in.


you can use:

(//@lang)[1]

these means you get all attributes nodes with name equal to "lang" and get the first one.


You can also get it by

string(//bookstore/book[1]/title/@lang)    
string(//bookstore/book[2]/title/@lang)

although if you are using XMLDOM with JavaScript you can code something like

var n1 = uXmlDoc.selectSingleNode("//bookstore/book[1]/title/@lang");

and n1.text will give you the value "eng"


If you are using PostgreSQL, this is the right way to get it. This is just an assumption where as you have a book table TITLE and PRICE column with populated data. Here's the query

SELECT xpath('/bookstore/book/title/@lang', xmlforest(book.title AS title, book.price AS price), ARRAY[ARRAY[]::TEXT[]]) FROM book LIMIT 1;

Thanks! This solved a similar problem I had with a data attribute inside a Div.

<div id="prop_sample" data-want="data I want">data I do not want</div>

Use this xpath: //*[@id="prop_sample"]/@data-want

Hope this helps someone else!


You can try below xPath pattern,

  XPathExpression expr = xPath.compile("/bookstore/book/title[@lang='eng']")

Here is the snippet of getting the attribute value of "lang" with XPath and VTD-XML.

import com.ximpleware.*;
public class getAttrVal {
    public static void main(String s[]) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false)){
            return ;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/bookstore/book/title/@lang");
        System.out.println(" lang's value is ===>"+ap.evalXPathToString());
    }
}