我找不到 Nokogiri 支持的 xpath 版本的官方声明。有人可以帮我吗?事实上,我想提取一些具有以指定子字符串开头的属性的元素。例如,我想获得所有Book
元素具有category
属性以字符开头C
。如何使用 nokogiri 做到这一点?
<?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>
我不知道 Nokogiri 支持哪个特定版本的 XPath。但是,你可以这样做:
我想得到全部book
元素具有category
属性以字符开头C
.
使用 XPath 的starts-with http://www.w3.org/TR/xpath/#function-starts-with:
doc = Nokogiri::XML(your_xml)
doc.search('//book[starts-with(@category, "C")]').each { |e| puts e['category'] }
# output is:
# COOKING
# CHILDREN
你也可以使用 CSS3“开始于”选择器 http://www.w3.org/TR/css3-selectors/#attribute-substrings:
doc = Nokogiri::XML(your_xml)
doc.search('book[category^=C]').each { |e| puts e['category'] }
# output is:
# COOKING
# CHILDREN
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)