Method: Nokogiri::XML::Node#attributes

Defined in:
lib/nokogiri/xml/node.rb

#attributesObject

:call-seq: attributes() → Hash<String ⇒ Nokogiri::XML::Attr>

Fetch this node’s attributes.

⚠ Because the keys do not include any namespace information for the attribute, in case of a simple name collision, not all attributes will be returned. In this case, you will need to use #attribute_nodes.

Returns

Hash containing attributes belonging to self. The hash keys are String attribute names (without the namespace), and the hash values are Nokogiri::XML::Attr.

Example with no namespaces:

doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
doc.at_css("child").attributes
# => {"size"=>#(Attr:0x550 { name = "size", value = "large" }),
#     "class"=>#(Attr:0x564 { name = "class", value = "big wide tall" })}

Example with a namespace:

doc = Nokogiri::XML("<root xmlns:desc='http://example.com/sizes'><child desc:size='large'/></root>")
doc.at_css("child").attributes
# => {"size"=>
#      #(Attr:0x550 {
#        name = "size",
#        namespace = #(Namespace:0x564 {
#          prefix = "desc",
#          href = "http://example.com/sizes"
#          }),
#        value = "large"
#        })}

Example with an attribute name collision:

⚠ Note that only one of the attributes is returned in the Hash.

doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'
        xmlns:height='http://example.com/heights'>
    <child width:size='broad' height:size='tall'/>
  </root>
EOF
doc.at_css("child").attributes
# => {"size"=>
#      #(Attr:0x550 {
#        name = "size",
#        namespace = #(Namespace:0x564 {
#          prefix = "height",
#          href = "http://example.com/heights"
#          }),
#        value = "tall"
#        })}


609
610
611
612
613
# File 'lib/nokogiri/xml/node.rb', line 609

def attributes
  attribute_nodes.each_with_object({}) do |node, hash|
    hash[node.node_name] = node
  end
end