2011-08-26 118 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