require 'xml/libxml'
require 'libxml/document'
$release_date
doc=LibXML::XML::Parser.io(file.xml).parse
doc.root.each_element('//ABCD/xyz/') do |elem|
elem.each_element do |node|
node.each_element do |child|
if child.content=="ABCD"
$release_date=node['date']
else
if node['type']=="Original"
$release_date=node['date']
end
end
end
end
end
puts "Release date : #{$release_date}"
This is the code that I've written to extract a particular date from an XML file according to my requirements. I've used lib xml library but am getting the following errors:
`parse': undefined method `read' for "file.xml":String (NoMethodError)
As per libxml documentation, to parse a file:
LibXML::XML::Parser.file('file.xml').parse
or
LibXML::Parser.io(File.open('file.xml')).parse
Also, each_element
doesn’t take any parameter. If you want to do an XPath query, have a look at find:
require 'xml'
doc = LibXML::XML::Parser.file("/tmp/test.xml").parse
nodes = doc.find('//test')
nodes.each do |n|
puts n.content
end