George Jor
George Jor

Reputation: 511

How can I get all attributes from nokogiri nodeset

As in Nokogiri::XML::Element, there is a method called attributes to get all as a hash. While for NodeSet object, there are no such method and we need to specify attribute key to get its value. I know that xpath have the ability to extract attributes but I couldn't think of the solutions of the following situation:

Normally, there is only one attr called match-type in match element document:

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

But now, I need to assume only matct-type attr is allowed in this element tag:

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

My idea is to get all attributes inside this element and find out the size of the attributes other than 'match-type'.

Any solution that I can do that? Thanks!

Upvotes: 1

Views: 1249

Answers (1)

the Tin Man
the Tin Man

Reputation: 160551

This isn't going to directly answer your question, because it's not clear whether you've tried anything. Instead, this code can be modified to do what you want but you're going to need to figure out what to change:

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]

Upvotes: 1

Related Questions