From: Gavin Kistner Date: 2011-09-05T22:01:11+09:00 Subject: Re: Ruby and XML On Sep 5, 2011, at 1:28 AM, 7stud -- wrote: > 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 = element.next_element > puts sibling.text > else > puts "No tag that is a sibling" > end > > puts "-" * 20 > end 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 Output: name: Tove Tove's value is: 10 -------------------- name: Jani Jani's value is: 20 -------------------- name: No sibling No tag that is a sibling -------------------- Again using this XML: Tove Tove's value is: 10 xxxx Tove Jani Reminder Don't forget me this weekend! Jani Jani's value is: 20 xxxx No sibling No sibling's value is: 30