Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attribute using XPath

Tags:

xml

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?

like image 417
GurdeepS Avatar asked Dec 25 '10 22:12

GurdeepS


People also ask

What is attribute in XPath?

Definition of XPath attribute. For finding an XPath node in an XML document, use the XPath Attribute expression location path. We can use XPath to generate attribute expressions to locate nodes in an XML document.

How do I navigate to parent node in XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.

What is XPath function?

XPath can be used to navigate through elements and attributes in an XML document. XPath is a syntax for defining parts of an XML document. XPath uses path expressions to navigate in XML documents. XPath contains a library of standard functions. XPath is a major element in XSLT and in XQuery.


1 Answers

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) 
like image 86
Dimitre Novatchev Avatar answered Sep 19 '22 11:09

Dimitre Novatchev