问题描述
我找不到 Nokogiri 支持的 xpath 版本的官方声明.任何人都可以帮助我吗?事实上,我想提取一些具有以指定子字符串开头的属性的元素.例如,我想获取所有具有 category
属性以字符 C
开头的 Book
元素.如何用 nokogiri 做到这一点?
I can't find an official statement of the xpath version that Nokogiri supports. Anyone can help me with it? In fact I want to extract some elements that have an attribute start with specified sub string. For example, I want to get all Book
elements that have a category
attribute start with the character C
. How to do this with 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>
推荐答案
我不知道 XPath Nokogiri 支持哪个特定版本.但是,您可以这样做:
I don't know which specific version of XPath Nokogiri supports. But, you can do this:
我想获取所有具有 category
属性以字符 C
开头的 book
元素.
使用 XPath 的 starts-with
:
using XPath's starts-with
:
doc = Nokogiri::XML(your_xml)
doc.search('//book[starts-with(@category, "C")]').each { |e| puts e['category'] }
# output is:
# COOKING
# CHILDREN
您也可以使用 CSS3 开头为"选择器:
You could also use a CSS3 "begins with" selector:
doc = Nokogiri::XML(your_xml)
doc.search('book[category^=C]').each { |e| puts e['category'] }
# output is:
# COOKING
# CHILDREN
这篇关于Nokogiri 支持哪个版本的 xpath?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!