【问题标题】:How can I get all attributes from nokogiri nodeset如何从 nokogiri 节点集中获取所有属性
【发布时间】:2014-10-30 04:36:33
【问题描述】:

在 Nokogiri::XML::Element 中,有一种称为属性的方法可以将所有内容作为散列获取。而对于 NodeSet 对象,没有这样的方法,我们需要指定属性键来获取它的值。我知道xpath有提取属性的能力但是我想不出以下情况的解决方案:

通常情况下,match元素文档中只有一个attr叫做match-type:

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

但是现在,我需要假设这个元素标签中只允许使用 matct-type attr:

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

我的想法是获取该元素内的所有属性,并找出除“匹配类型”之外的属性的大小。

我可以做到这一点的任何解决方案?谢谢!

【问题讨论】:

  • 您是否为此编写了代码,还是要求我们为您编写?

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


【解决方案1】:

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

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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 2012-06-05
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多