Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I 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 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?

like image 825
maerics Avatar asked Apr 23 '14 14:04

maerics


People also ask

How do I find the root tag in XML?

In any markup language, the first element to appear is called the "root element", which defines what kind of document the file will be. In an HTML file, the <html> tag is the root element. An HTML file will always have the HTML element as the root element, while in an XML file, it can be anything.

What are root nodes in XML?

The root node is the parent of all other nodes in the document. An immediate descendant of another node. Note that element attributes are not generally considered child elements.

What is the use of Nokogiri?

Nokogiri (htpp://nokogiri.org/) is the most popular open source Ruby gem for HTML and XML parsing. It parses HTML and XML documents into node sets and allows for searching with CSS3 and XPath selectors. It may also be used to construct new HTML and XML objects.

Which gem is used to parse a .XML or .HTML document?

To parse XML-documents, I recommend the gem nokogiri .


1 Answers

/* 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"
like image 98
Stefan Avatar answered Sep 20 '22 19:09

Stefan