How to parse xml files with nokogiri and put the results in a new file?
nokogiri, ruby, xml
Solution
The following makes a few assumptions about your situation that may be incorrect (namely, that "city" is a node and not an attribute, and that all the files are in a single directory), but you should be able to tweak it to suit your needs.
require 'rubygems'
require 'nokogiri'
Dir.glob("*.xml").each do |filename|
input = Nokogiri::XML(File.new(filename))
output = Nokogiri::XML::Document.new
output.root = Nokogiri::XML::Node.new("output", output)
input.root.xpath("//*[city='London']").each {|n| output.root << n}
File.open("out_" + filename, 'w') {|f| f.write(output.to_xml) }
end
Problem
I'm just beginning with Nokogiri and have a question, hope you guys can help me out: - I need to parse a set of XML files (let's say 5 files). - Find elements with specific values, for instance, City = "London" using XPATH. - Create a new XML file, that contains the results of the previous XPATH query in Step 2