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>
</boo开发者_如何学运维k>
<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?
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)
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']")
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.
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;
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"
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());
}
}
精彩评论