REXML ruby next element

62 views Asked by At

I'm trying to get element and next element from XML

<way>
 <nd ref="4979923479"/>
 <nd ref="4979923478"/>
 <nd ref="5721236634"/>
 <nd ref="5721236635"/>
 <nd ref="5721236636"/>
 <nd ref="5721236637"/>
 <nd ref="4979923477"/>
 <nd ref="5721236638"/>
 <nd ref="5721236639"/>
</way>

Here what I have tried to do, but instead of "puts i.attributes["ref"]" I need something like "puts "#{i.attributes["ref"]} -> i.next (i+1).attributes["ref"]

require "rexml/document"
include REXML
inputFileName = ARGV[0]
file = File.new(inputFileName)
doc = Document.new(file)

doc.elements.each("way/nd") do |i|
    if i.next != nil
        puts i.attributes["ref"]
    end
end

Actual output is just list of all nd's

4979923479
4979923478
5721236634
5721236635
5721236636
5721236637
4979923477
5721236638
5721236639

Desired output is:

4979923479 -> 4979923478
4979923478 -> 5721236634
5721236634 -> 5721236635
5721236635 -> 5721236636
5721236636 -> 5721236637
5721236637 -> 4979923477
4979923477 -> 5721236638
5721236638 -> 5721236639
1

There are 1 answers

1
infused On BEST ANSWER

I think you want to use next_element instead. This produces the desired output:

require "rexml/document"
include REXML
inputFileName = ARGV[0]
file = File.new(inputFileName)
doc = Document.new(file)

doc.elements.each("way/nd") do |i|
  next unless i.next_element
  puts "#{i.attributes["ref"]} -> #{i.next_element.attributes['ref']}"
end