我用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地圖中後,這些點將放置在正確的地址/座標處,但左側邊欄上每個引腳旁邊的名稱/描述符只會顯示「?」而不是顯示地址。
我想用一個正則表達式找到每個"<name>?</name>"
,然後使用正則表達式查找的文件中<address>.*</address>
下一個實例,然後回去與*
那是<address>
標籤之間更換<name>
標籤之間的?
。
每個點的<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
UPDATE:在原來的服務(BatchGeo)有設置裏面有什麼KML(XML)標籤中有哪些信息的選項,所以我創建了一張新地圖,並首先防止了該問題的發生。感謝那些向我推薦我可以在將來使用這種操作的工具。
更新2:嘗試Mark Thomas的解決方案。這是我跑的代碼:
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次)。
[Nokogiri](http://nokogiri.org/)。 – harbichidian
使用XML解析器來處理XML,就像echoback所建議的一樣。 – nhahtdh
謝謝,我不知道這樣的事情存在。現在閱讀文檔 - 看起來Nokogiri會有解決方案。我會在這裏更新,如果我找到一個。 –