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?
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.
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.
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.
To parse XML-documents, I recommend the gem nokogiri .
/*
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With