Skip to content

Instantly share code, notes, and snippets.

@Pistos
Created March 13, 2009 15:38
Show Gist options
  • Save Pistos/78614 to your computer and use it in GitHub Desktop.
Save Pistos/78614 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby19
require 'rexml/document'
class XMLGenealogy
INDENTATION = ' '
def initialize( argv )
@namespace_uri = argv[ 0 ]
@dir_mask = argv[ 1 ]
if @namespace_uri.nil? || @namespace_uri == '--help' || @dir_mask.nil?
puts "#{$0} <namespace URI> [dir mask]"
exit 1
end
@ancestry = Hash.new { |hash,key| hash[ key ] = Array.new }
@genealogy = Hash.new { |hash,key| hash[ key ] = Hash.new }
end
def spider
Dir[ @dir_mask ].each do |f|
doc = REXML::Document.new File.new( f )
REXML::XPath.each(
doc,
"//*[namespace-uri()='#{@namespace_uri}' or @*[namespace-uri()='#{@namespace_uri}'] ]"
).each do |element|
p = element.parent
@ancestry[ "#{element.prefix}:#{element.name}" ] << "#{p.prefix}:#{p.name}"
end
break # debugging
end
@ancestry.each do |element,seen_parents|
seen_parents.each do |parent|
@genealogy[ parent ][ element ] = true
end
end
end
def print_children( parent, level )
puts "#{INDENTATION*level}#{parent}"
@genealogy[ parent ].keys.sort.each do |child|
print_children( child, level + 1 )
end
end
def report
@genealogy.each_key do |parent|
print_children parent, 0
end
end
end
xg = XMLGenealogy.new( ARGV.dup )
xg.spider
xg.report
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment