Question

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

I thought that doing an XPath query for / would do the trick but apparently that node name is "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 node name without knowing it ahead of time?

Was it helpful?

Solution

/* 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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top