Created
December 10, 2011 10:59
-
-
Save manveru/1454937 to your computer and use it in GitHub Desktop.
Grepping XML using XPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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