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
Share:
11,625
Admin
Author by

Admin

Updated on July 06, 2022

Comments

  • Admin
    Admin almost 2 years

    I'm just beginning with Nokogiri and have a question, hope you guys can help me out:

    1. I need to parse a set of XML files (let's say 5 files).
    2. Find elements with specific values, for instance, City = "London" using XPATH.
    3. Create a new XML file, that contains the results of the previous XPATH query in Step 2