Getting attribute using XPath

GurdeepS picture GurdeepS · Dec 25, 2010 · Viewed 391.6k times · Source

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?

Answer

Dimitre Novatchev picture Dimitre Novatchev · Dec 26, 2010

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

Use:

/*/book[1]/title/@lang

This means:

Select the lang attribute of the title element that is a child of the first book child of the top element of the XML document.

To get just the string value of this attribute use the standard XPath function string():

string(/*/book[1]/title/@lang)