How to parse xml files with nokogiri and put the results in a new file?
11,625
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
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on July 06, 2022Comments
-
Admin almost 2 years
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