问题
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?
回答1:
/*
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"
来源:https://stackoverflow.com/questions/23248091/how-do-i-get-the-root-element-name-of-an-xml-document-using-nokogiri