Skip to content

Instantly share code, notes, and snippets.

@yeban
Created May 18, 2010 00:06
Show Gist options
  • Save yeban/404410 to your computer and use it in GitHub Desktop.
Save yeban/404410 to your computer and use it in GitHub Desktop.
Simple demo script for ruby libxml's reader api.
require "rubygems"
require "xml"
#parse the sample.xml ignoring whitespaces and
#performing entity substitution.
doc = XML::Reader.file("sample.xml", :options => XML::Parser::Options::NOBLANKS |
XML::Parser::Options::NOENT
)
#display a node's name: local and prefix
def display_name( node )
puts "\tName: #{node.name}"
if node.prefix
puts "\t\tPrefix: #{node.prefix}" if node.prefix
puts "\t\tLocal: #{node.local_name}"
end
end
#display attributes of a node
def display_attributes( node )
node.attribute_count.times do | index |
puts "Attribute # #{index + 1}"
node.move_to_next_attribute
display node
end
node.move_to_element
end
#process a node
def display( node )
display_name node
puts "\tDepth: #{node.depth}"
puts "\tEmpty Element" if node.empty_element?
puts "\tValue: #{node.value}" if node.has_value?
display_attributes node
print "\n"
end
#shift through the document.
i = 1
while doc.read
unless doc.node_type == XML::Reader::TYPE_END_ELEMENT
puts "Node # #{i}"
display doc
i += 1
end
end
#free the resources
doc.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment