Skip to content

Instantly share code, notes, and snippets.

@manveru
Created December 10, 2011 10:59
Show Gist options
  • Save manveru/1454937 to your computer and use it in GitHub Desktop.
Save manveru/1454937 to your computer and use it in GitHub Desktop.
Grepping XML using XPath
#!/usr/bin/env ruby
# Usage:
# xgrep.rb '//load[@module]/@module' autoload_configs/modules.conf.xml
require 'nokogiri'
xpath = ARGV[0]
files = ARGV[1..-1]
def output(results)
case results
when Nokogiri::XML::Attr
puts results.value
when Array, Nokogiri::XML::NodeSet
results.each{|result| output(result) }
when String
puts results
else
puts "The following are the contents I couldn't handle"
p results
abort "Don't know how to handle #{results.class}, please fix me."
end
end
files.each do |file|
File.open(file) do |io|
output(Nokogiri::XML(io).xpath(xpath))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment