如何从nokogiri nodeset获取所有属性

时间:2014-10-30 04:36:34

标签: ruby-on-rails ruby xml xpath nokogiri

与Nokogiri :: XML :: Element一样,有一个名为attributes的方法可以将all作为哈希。对于NodeSet对象,没有这样的方法,我们需要指定属性键来获取其值。我知道xpath具有提取属性的能力,但我无法想到以下情况的解决方案:

通常,匹配元素文档中只有一个名为match-type的attr:

<D:match match-type="starts-with">appren</D:match>

但现在,我需要假设此元素标记中只允许使用matct-type attr:

<D:match caseless="bogus" match-type="starts-with">appren</D:match>

我的想法是获取此元素中的所有属性,并找出&#39; match-type&#39;以外的属性的大小。

我能做到的任何解决方案吗?谢谢!

1 个答案:

答案 0 :(得分:0)

这不会直接回答你的问题,因为你是否已经尝试过任何事情并不清楚。相反,可以修改此代码以执行您想要的操作,但您需要确定要更改的内容:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<html>
  <body>
    <a id="some_id" href="/foo/bar/index.html" class='bold'>anchor text</a>
    <a id="some_other_id" href="/foo/bar/index2.html" class='italic'>anchor text</a>
  </body>
</html>
EOT

doc.search('a').map{ |node| node.keys.reject{ |k| k == 'id' }.map{ |p| node[p].size }.inject(:+) } # => [23, 26]
相关问题