Last active
August 29, 2015 14:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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