且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-25 09:13:04

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'.