tags:

views:

2996

answers:

1

Hello all, 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 value (for instance, City = "London"), with XPATH.

3) Have a new xml file, with the results of the previous xpath parsing.

+6  A: 

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
Greg Campbell