如何使用Nokogiri获取XML文档的根元素名称?

时间:2022-10-31 18:25:04

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

使用Nokogiri,我想确定根元素的名称。

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

我认为对/做一个XPath查询可以做到这一点,但显然节点名称是“文档”?

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?

如何在不事先知道根节点名的情况下获取字符串“foo”?

1 个解决方案

#1


9  

/* should work:

/* 应该管用:

require 'nokogiri'
doc = Nokogiri::XML('<foo>Hello</foo>')

doc.xpath('/*').first.name
#=> "foo"

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

或使用Nokogiri :: XML :: Document #root:

doc.root.name
#=> "foo"

#1


9  

/* should work:

/* 应该管用:

require 'nokogiri'
doc = Nokogiri::XML('<foo>Hello</foo>')

doc.xpath('/*').first.name
#=> "foo"

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

或使用Nokogiri :: XML :: Document #root:

doc.root.name
#=> "foo"