How to get the root element name of an XML document using Nokogiri?

Using Nokogiri, I would like to determine the name of the root element.

I thought that running an XPath query for / would do the trick, but apparently the node name is a "document"?

 require 'nokogiri' doc = Nokogiri::XML('<foo>Hello</foo>') doc.xpath('/').first.name # => "document" doc.xpath('/foo').first.name # => "foo" 

How can I get the string "foo" for the root root name without knowing it ahead of time?

+6
source share
1 answer

/* should work:

 require 'nokogiri' doc = Nokogiri::XML('<foo>Hello</foo>') doc.xpath('/*').first.name #=> "foo" 

or using Nokogiri::XML::Document#root :

 doc.root.name #=> "foo" 
+9
source

All Articles