Skip to content

Instantly share code, notes, and snippets.

@streetcarmonkey
Last active August 29, 2015 14:12
Show Gist options
  • Save streetcarmonkey/e88333cae7c25b4b4e65 to your computer and use it in GitHub Desktop.
Save streetcarmonkey/e88333cae7c25b4b4e65 to your computer and use it in GitHub Desktop.
How to get all nodes or elements in a html or xml document using Ruby, Nokogiri and xpath.
require 'rubygems'
require 'nokogiri'
xml = <<EOF
<Guide>
<Master>
<Part>12345</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>B</Name>
</Sub>
</Master>
<Master>
<Part>XYZABC</Part>
<Sub>
<Name>A</Name>
</Sub>
<Sub>
<Name>C</Name>
</Sub>
</Master>
</Guide>
EOF
doc = Nokogiri::XML::DocumentFragment.parse(xml)
puts doc.xpath(".//*").size # => Should be 13
doc.xpath(".//*").each do | node |
puts node.name
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment