我使用BatchGeo从电子表格创建地图,然后下载KML数据,即:

<Placemark>
  <name>?</name>
    <Snippet></Snippet>
    <description><![CDATA[]]></description>
    <styleUrl>#style75</styleUrl>
    <address>1234 Example St Denver, CO 80221</address>
    <Point>
      <coordinates>-121.879364,37.815151,0.000000</coordinates>
    </Point>
</Placemark>

当导入回Google地图时,这些点被放置在正确的地址/坐标上,但是左侧边栏上每个管脚旁边的名称/描述符只显示“?”而不是显示地址。
我想使用regex查找每个"<name>?</name>",然后使用regex查找文件中<address>.*</address>的下一个实例,然后返回并用?标记之间的<name>替换*标记之间的<address>
每个点的<Placemark>标记之间有一个代码块,总共有数百个点。
以下是我目前掌握的零碎资料:
newkml = File.open( 'Newkml.txt', 'w' )

def process_line(x)
  unless x == "<name>?</name>"
    # just return the original line
  else
    # Find the next instance of /<address>(.*)<\/address>/
    # Go to the original line
    # Replace it with "<name>#{$1}</name>"
  end
end

File.foreach('Whatever.kml'){|line|} do line.process_line
# Make a new file, copy over all of the lines that aren't <name>?</name>,
# and fix the name lines using the method above

更新:在原始服务(batchgeo)中,有一个选项可以设置kml(xml)标记中的信息,因此我创建了一个新的映射,并在第一时间防止了问题的发生。感谢那些推荐我使用将来可以用于此类操作的工具的人。
更新2:尝试马克·托马斯的解决方案这是我运行的代码:
require 'rubygems'
require 'nokogiri'

doc = Nokogiri::XML("whatever.xml")

edits = 0

doc.xpath("//name").each do |name|
  if name.content == "?"
    name.content = name.xpath("following-sibling::address").text
    edits +=1
  end
end

puts( doc.inspect )
puts( "edits: #{edits}" )
puts doc

这将提供以下输出:
#<Nokogiri::XML::Document:0xfe0064 name="document>
edits: 0
<?xml version="1.0"?>

如果我添加的edits测试代码按我认为的那样工作,则似乎表明if name.content == "?"块执行了0次(比我预期的少130次)。

最佳答案

已经为您完成了用几乎任何语言解析/生成KML文件的工作我想这个对你有用:https://github.com/schleyfox/ruby_kml
更新
由于没有实际使用上述库,我想确认我的建议-看起来所有的helper函数都用于创建kml文件,但是仍然需要使用xml解析器来加载一个。我仍然建议,这比使用建议的xml解析器操纵kml要好(尽管这肯定也能很好地工作),但是您可能还想看看支持kml输入和输出的http://georuby.rubyforge.org/georuby-doc/index.html
更新2-为后代添加。
在我的回答中再考虑一下,我对这类问题的默认建议是:
将KML解析为对象
改正错误
重新生成kml
我的理由是,这应该不太容易破坏输出,如果你最终开始对KML进行更多的操作,你已经达到了90%的效果。
所有这些都表明,在您的特定情况下,为了只对已知数据进行标识更改,@Mark Thomas的方法将提供一个更快、低代码开销的解决方案。

关于ruby - 使用正则表达式查找字符串,然后使用正则表达式查找新字符串以替换为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14370790/

10-12 00:10
查看更多