Skip to content

Instantly share code, notes, and snippets.

@streetcarmonkey
Last active August 29, 2015 14:22
Show Gist options
  • Save streetcarmonkey/14ed9a93b2ba73468668 to your computer and use it in GitHub Desktop.
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.
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