我正在尝试从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>
这是我尝试做的事情,但是除了“ puts i.attributes [“ ref”]“”之外,我需要的是“ 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
实际输出只是所有nd的列表
4979923479
4979923478
5721236634
5721236635
5721236636
5721236637
4979923477
5721236638
5721236639
所需的输出是:
4979923479 -> 4979923478
4979923478 -> 5721236634
5721236634 -> 5721236635
5721236635 -> 5721236636
5721236636 -> 5721236637
5721236637 -> 4979923477
4979923477 -> 5721236638
5721236638 -> 5721236639
答案 0 :(得分:0)
我认为您想改用next_element
。这样会产生所需的输出:
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