4

我正在尝试从 KML 文件中提取两个不同的元素并将它们转换为 CSV。我从这里的很棒的网站开始:http ://ckdake.com/content/2012/highgroove-hack-night-kml-heatmaps.html ,它会生成一个坐标的csv。我现在要做的就是将名称标签添加到每行的开头。我是 ruby​​/nokogiri n00b,所以我可以粘贴这段代码,让我得到 a) 所有名称的列表,然后是 b) 所有坐标的列表。但同样 - 我希望他们在同一条线上。

require 'rubygems'
require 'nokogiri' # gem install nokogiri

@doc = Nokogiri::XML(File.open("WashingtonDC2013-01-04 12h09m01s.kml"))

@doc.css('name').each do |name|  
  puts name.content
end

@doc.css('coordinates').each do |coordinates|
  coordinates.text.split(' ').each do |coordinate|
    (lat,lon,elevation) = coordinate.split(',')
    puts "#{lat},#{lon}\n"
  end
end
4

1 回答 1

7

这个怎么样:

@doc.css('Placemark').each do |placemark|
  name = placemark.css('name')
  coordinates = placemark.at_css('coordinates')

  if name && coordinates
    print name.text + ","
    coordinates.text.split(' ').each do |coordinate|
      (lon,lat,elevation) = coordinate.split(',')
      print "#{lat},#{lon}"
    end
    puts "\n"
  end
end

我在这里假设<coordinates>每个<Placemark>. 如果还有更多,它们都会被附加到同一行。

If that doesn't work, you'll need to post some of the KML file itself so I can test on it. I'm just guessing based on this sample KML file.

于 2013-01-08T06:30:45.013 回答