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

試著忘記壹切 提交于 2019-12-07 03:47:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!