From: 7stud -- Date: 2011-09-06T01:28:10+09:00 Subject: Re: Ruby and XML Gavin Kistner wrote in post #1020210: > > For comparison, here's one way to write code with the similar > functionality using Nokogiri, but ensuring that the element is a > sibling of the element. Unlike the above code, the following > allows any number of elements between the and the : > require 'nokogiri' > > doc = Nokogiri::XML(IO.read("my.xml")) > doc.search('name').each do |name| > puts "name: #{name.text}" > if value=name.at_xpath('following-sibling::value') > puts value.text > else > puts "No tag that is a sibling" > end > puts "-" * 20 > end > I couldn't figure out the syntax for xpath's following-sibling, but now that I see it in your code, here it is in REXML: require 'rexml/document' f = File.new("xml.xml") doc = REXML::Document.new(f) REXML::XPath.each(doc, "//name") do |element| puts "name: #{element.text}" if sibling = REXML::XPath.match(element, "following-sibling::value").first puts sibling.text else puts "Can't find a tag that is a sibling" end puts "-" * 20 end And here is some trickier xml that exercises 'following-sibling::value': Tove xxxx Tove's value is: 10 Tove Jani Reminder Don't forget me this weekend! Jani xxxx xxxx Jani's value is: 20 1200 Diane Diane's value is: 30 --output:-- name: Tove Tove's value is: 10 -------------------- name: Jani Jani's value is: 20 -------------------- name: Diane Can't find a tag that is a sibling -------------------- -- Posted via http://www.ruby-forum.com/.