2011-08-26 117 views
2

我找不到Nokogiri支持的xpath版本的官方聲明。任何人都可以幫助我嗎?實際上,我想提取一些具有以指定子字符串開頭的屬性的元素。例如,我想讓所有Book屬性的category屬性以字符C開頭。如何用nokogiri做到這一點?Nokogiri支持哪個版本的xpath?

<?xml version="1.0" encoding="ISO-8859-1"?> 
<!-- Edited by XMLSpy?--> 
<bookstore> 

<book category="COOKING"> 
    <title lang="en">Everyday Italian</title> 
    <author>Giada De Laurentiis</author> 
    <year>2005</year> 
    <price>30.00</price> 
</book> 

<book category="CHILDREN"> 
    <title lang="en">Harry Potter</title> 
    <author>J K. Rowling</author> 
    <year>2005</year> 
    <price>29.99</price> 
</book> 

<book category="WEB"> 
    <title lang="en">XQuery Kick Start</title> 
    <author>James McGovern</author> 
    <author>Per Bothner</author> 
    <author>Kurt Cagle</author> 
    <author>James Linn</author> 
    <author>Vaidyanathan Nagarajan</author> 
    <year>2003</year> 
    <price>49.99</price> 
</book> 

<book category="WEB"> 
    <title lang="en">Learning XML</title> 
    <author>Erik T. Ray</author> 
    <year>2003</year> 
    <price>39.95</price> 
</book> 

</bookstore> 
+0

[「引入nokogiri僅支持XPath 1.0和不支持的XPath 2.0,該令牌化()是首先定義在。「](https://github.com/sparklemotion/nokogiri/issues/957)。這些限制是由於libxml2和javax.xml.xpath引起的 – jtzero

回答

2

我不知道XPath Nokogiri支持哪個特定版本。但是,你可以這樣做:

我希望得到的是有一個category屬性開始以字符C所有book元素。

使用XPath的starts-with

doc = Nokogiri::XML(your_xml) 
doc.search('//book[starts-with(@category, "C")]').each { |e| puts e['category'] } 
# output is: 
# COOKING 
# CHILDREN 

您也可以使用CSS3 "begins with" selector

doc = Nokogiri::XML(your_xml) 
doc.search('book[category^=C]').each { |e| puts e['category'] } 
# output is: 
# COOKING 
# CHILDREN