Last active
August 29, 2015 14:22
-
-
Save streetcarmonkey/14ed9a93b2ba73468668 to your computer and use it in GitHub Desktop.
Ruby Nokogiri: Return a parent attribute value based on a sub element attribute match.
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
xml = " | |
<levels> | |
<lvl attr = 'x'> | |
<lvl2> | |
<lvl3 n = 'unique_value 1A'>'</lvl3> | |
</lvl2> | |
</lvl1> | |
<lvl attr = 'y' another_attr = 'z'> | |
<lvl2> | |
<lvl3 n = 'unique_value 1B'>'</lvl3> | |
</lvl2> | |
</lvl1> | |
</levels> | |
" | |
require 'nokogiri' | |
require 'pp' | |
doc = Nokogiri::XML(xml) | |
puts "Should return 'y'" | |
puts element = doc.at_xpath(".//*/*[@n='unique_value 1B']") | |
puts attribute = (element.ancestors('lvl').first || { })['attr'] | |
puts '' | |
puts "Should return 'x'" | |
puts element = doc.at_xpath(".//*/*[@n='unique_value 1A']") | |
puts attribute = (element.ancestors('lvl').first || { })['attr'] | |
puts '' | |
puts "Should dump all parent attributes" | |
puts element = doc.at_xpath(".//*/*[@n='unique_value 1B']") | |
puts attributes = (element.ancestors('lvl').first || { }).attributes() | |
attributes.each { | k, v | pp "#{k}: #{v}" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment