Created
September 5, 2011 14:27
-
-
Save rklemme/1195114 to your computer and use it in GitHub Desktop.
Solutions for ruby-talk 387408
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
#!/bin/env ruby19 | |
require 'pp' | |
require 'nokogiri' | |
doc = Nokogiri::XML(DATA) | |
doc.xpath('//name[following-sibling::value]').each do |name| | |
value = name.xpath('following-sibling::value[1]').first | |
# pp value, value.size | |
p [name.text, value.text] | |
end | |
puts '--------------' | |
# all "name" tags which do not have a following sibling "value" tag | |
doc.xpath('//name[not(following-sibling::value)]').each do |name| | |
p name.text | |
end | |
puts '--------------' | |
# all "name" tags whose next following sibling is not a "value" tag | |
doc.xpath('//name[following-sibling::*[1][name()!="value"]]').each do |name| | |
p name.text | |
end | |
puts '--------------' | |
# all "name" tags which do not have exactly one following sibling "value" tag | |
doc.xpath('//name[count(following-sibling::value)!=1]').each do |name| | |
p name.text | |
end | |
puts '--------------' | |
# all "name" tags whose next following sibling is not a "value" tag OR | |
# which do not have exactly one following sibling "value" tag | |
doc.xpath('//name[following-sibling::*[1][name()!="value"]]|//name[count(following-sibling::value)!=1]').each do |name| | |
p name.text | |
end | |
__END__ | |
<?xml version="1.0"?> | |
<note> | |
<name>Tove</name> | |
<value>Tove's value is: 10</value> | |
<garbage>xxxx</garbage> | |
<to>Tove</to> | |
<from>Jani</from> | |
<heading>Reminder</heading> | |
<body>Don't forget me this weekend!</body> | |
<parent> | |
<name>Jani</name> | |
<value>Jani's value is: 20</value> | |
<garbage>xxxx</garbage> | |
</parent> | |
<parent> | |
<name>Too many</name> | |
<value>Wrong's value is: 30</value> | |
<value>Mr. Wrong</value> | |
<garbage>xxxx</garbage> | |
</parent> | |
<parent> | |
<name>Missing</name> | |
<garbage>xxxx</garbage> | |
</parent> | |
<parent> | |
<name>No sibling</name> | |
</parent> | |
<value>No sibling's value is: 30</value> | |
</note> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment