Skip to content

Instantly share code, notes, and snippets.

@briandunn
Created February 24, 2012 19:36
Show Gist options
  • Save briandunn/1903192 to your computer and use it in GitHub Desktop.
Save briandunn/1903192 to your computer and use it in GitHub Desktop.
Lothesome Nokogiri xmlns
xml = %|<?xml version="1.0" ?><foo xmlns="http://www.github.com"><bar/></foo>|
doc = Nokogiri xml
# Namespace is making me sad :(
doc.xpath '//bar'
# => []
# I can introduce a new name for a namespace and use it in my query
doc.xpath '//corprate-douche:bar', 'corprate-douche' => 'http://www.github.com'
# => [#<Nokogiri::XML::Element name="bar" namespace=#<Nokogiri::XML::Namespace href="http://www.google.com">>]
# The default namespace's name is xmlns. booooo.
doc.xpath '//xmlns:bar'
# => [#<Nokogiri::XML::Element name="bar" namespace=#<Nokogiri::XML::Namespace href="http://www.google.com">>]
# but wait, xpath is a query language. Surly I can...
doc.xpath "//*[local-name() = 'bar']"
# => [#<Nokogiri::XML::Element name="bar" namespace=#<Nokogiri::XML::Namespace href="http://www.google.com">>]
# REXML is a namespace honeybadger
doc = REXML::Document.new xml
REXML::XPath.each(doc, '//bar').map
# => [<bar/>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment