使用 Nokogiri 获取元素中包含特定属性名称的所有节点 [英] Use Nokogiri to get all nodes in an element that contain a specific attribute name

查看:52
本文介绍了使用 Nokogiri 获取元素中包含特定属性名称的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 Nokogiri 提取包含特定属性名称的元素中的所有节点.

I'd like to use Nokogiri to extract all nodes in an element that contain a specific attribute name.

例如,我想在下面的文档中找到包含属性blah"的 2 个节点.

e.g., I'd like to find the 2 nodes that contain the attribute "blah" in the document below.

@doc = Nokogiri::HTML::DocumentFragment.parse <<-EOHTML
<body>
  <h1 blah="afadf">Three's Company</h1>
  <div>A love triangle.</div>
   <b blah="adfadf">test test test</b>
</body>
EOHTML

我在这个网站上找到了这个建议(如下):http://snippets.dzone.com/posts/show/7994,但它不会返回上例中的 2 个节点.它返回一个空数组.

I found this suggestion (below) at this website: http://snippets.dzone.com/posts/show/7994, but it doesn't return the 2 nodes in the example above. It returns an empty array.

# get elements with attribute:
elements = @doc.xpath("//*[@*[blah]]")

关于如何做到这一点的想法?

Thoughts on how to do this?

谢谢!我在这里找到了这个

Thanks! I found this here

推荐答案

elements = @doc.xpath("//*[@*[blah]]")

这不是一个有用的 XPath 表达式.它说要为您提供所有具有名为blah"的子元素的属性的元素.因为属性不能有子元素,所以这个 XPath 永远不会返回任何东西.

This is not a useful XPath expression. It says to give you all elements that have attributes that have child elements named 'blah'. And since attributes can't have child elements, this XPath will never return anything.

DZone 片段令人困惑,因为他们说

The DZone snippet is confusing in that when they say

elements = @doc.xpath("//*[@*[attribute_name]]")

内部方括号不是文字……它们在那里表明您输入了属性名称.而外部方括号文字.:-p

the inner square brackets are not literal... they're there to indicate that you put in the attribute name. Whereas the outer square brackets are literal. :-p

@ 之后,它们还有一个额外的 *.

They also have an extra * in there, after the @.

你想要的是

elements = @doc.xpath("//*[@blah]")

这将为您提供具有名为blah"的属性的所有元素.

This will give you all the elements that have an attribute named 'blah'.

这篇关于使用 Nokogiri 获取元素中包含特定属性名称的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆