Method: Nokogiri::XML::Node#namespaces

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

#namespacesObject

:call-seq:

namespaces() 

Fetch all the namespaces on this node and its ancestors.

Note that the keys in this hash XML attributes that would be used to define this namespace, such as "xmlns:prefix", not just the prefix.

The default namespace for this node will be included with key "xmlns".

See also #namespace_scopes

[Returns] Hash containing all the namespaces on this node and its ancestors. The hash keys are the namespace prefix, and the hash value for each key is the namespace URI.

Example:

doc = Nokogiri::XML("<root xmlns=\"http://example.com/root\" xmlns:in_scope=\"http://example.com/in_scope\">\n  <first/>\n  <second xmlns=\"http://example.com/child\"/>\n  <third xmlns:foo=\"http://example.com/foo\"/>\n</root>\n")
doc.at_xpath("//root:first", "root" => "http://example.com/root").namespaces
# => {"xmlns"=>"http://example.com/root",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}
doc.at_xpath("//child:second", "child" => "http://example.com/child").namespaces
# => {"xmlns"=>"http://example.com/child",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}
doc.at_xpath("//root:third", "root" => "http://example.com/root").namespaces
# => {"xmlns:foo"=>"http://example.com/foo",
#     "xmlns"=>"http://example.com/root",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}


1251
1252
1253
1254
1255
1256
1257
# File 'lib/nokogiri/xml/node.rb', line 1251

def namespaces
  namespace_scopes.each_with_object({}) do |ns, hash|
    prefix = ns.prefix
    key = prefix ? "xmlns:#{prefix}" : "xmlns"
    hash[key] = ns.href
  end
end