Skip to content

Instantly share code, notes, and snippets.

@tmtysk
Created May 29, 2009 18:19
Show Gist options
  • Save tmtysk/120115 to your computer and use it in GitHub Desktop.
Save tmtysk/120115 to your computer and use it in GitHub Desktop.
rexml v.s. libxml (searching by XPath expr)
require 'rubygems'
require 'rexml/document'
require 'libxml'
RUBY_VERSION # => "1.8.6"
REXML::Version # => "3.1.7.2"
LibXML::XML::LIBXML_VERSION # => "2.6.30"
xml = '<hoge><foo><foo/><bar/></foo></hoge>'
# initialize
rexml = REXML::Document.new(xml) # => <UNDEFINED> ... </>
libxml = LibXML::XML::Document.string(xml) # => <?xml version="1.0" encoding="UTF-8"?>
# search by XPath expr
xpath4rexml = 'descendant::[self::foo or self::bar]'
rexml.root.elements.to_a(xpath4rexml) # => [<foo> ... </>, <foo/>, <bar/>]
libxml.find(xpath4rexml) rescue "error" # => "error"
xpath4libxml = './/*[self::foo or self::bar]'
libxml.find(xpath4libxml) # => #<LibXML::XML::XPath::Object:0x11b9490>
libxml.find(xpath4libxml).collect { |e| e.to_s } # => ["<foo>\n <foo/>\n <bar/>\n</foo>", "<foo/>", "<bar/>"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment