Skip to content

Instantly share code, notes, and snippets.

@maliqq
Created February 13, 2013 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maliqq/4946007 to your computer and use it in GitHub Desktop.
Save maliqq/4946007 to your computer and use it in GitHub Desktop.
require 'nokogiri'
require 'active_support/all'
def traverse(nodes, tabs = 0)
nodes.each do |node|
unless node.is_a? Nokogiri::XML::Element
if node.is_a?(Nokogiri::XML::Text)
puts ' ' * tabs + node.content.sub(/^\s+/, '').inspect if node.content !~ /^\s+$/
end
next
end
attrs = node.attributes
name = attrs.delete 'name'
attrs = attrs.map { |(key, value)|
v = value.content
v = case v
when /^-?\d+$/
v.to_i.inspect
when /^xs:.+$/
":#{v.sub('xs:', '')}"
when String
v.inspect
end
"#{key.underscore}: #{v}"
}.join(", ")
print "#{' ' * tabs}#{node.name.underscore}"
if name
print " #{name.content.inspect}"
print "," unless attrs.empty?
end
print " #{attrs}" unless attrs.empty?
unless node.children.empty?
puts " do"
traverse node.children, tabs + 2
puts "#{' ' * tabs}end"
else
puts
end
end
end
File.open('XMLSchema.xsd') { |f|
xml = Nokogiri::XML(f.read)
traverse xml.children
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment