我的研究发现使用 XPath 和/或 xml ElementTree 应该可以工作,但是使用以下代码(我知道它需要一些工作——python 的新手),我无法产生我正在寻找的结果。
我正在寻找将我的 kml 中超过单个字符的任何名称标签替换为空白字符串。我想保留元素树的结构,因为有重要的文件夹和子文件夹,因此由于未知缩进,逐行 string.replace 方法可能不起作用。
任何帮助将不胜感激,这是我到目前为止所拥有的。
import sys, string, os, lxml
import xml.etree.ElementTree as ET
kml_file = open(r'C:\temp\doc.kml', 'r')
tree = ET.parse(kml_file)
root = tree.getroot()
for name in root.findall('.//{http://www.opengis.net/kml/2.2}name'):
if len(name.text) > 1:
name.text = ""
kml_file.close()
示例 KML 代码:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>
<name>TempFile.kmz</name>
<open>1</open>
<StyleMap id="msn_ylw-pushpin">
<Pair>
<key>normal</key>
<styleUrl>#sn_ylw-pushpin3</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#sh_ylw-pushpin0</styleUrl>
</Pair>
</StyleMap>
<Style id="sn_ylw-pushpin3">
<IconStyle>
<scale>1.1</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<Style id="sh_ylw-pushpin0">
<IconStyle>
<scale>1.3</scale>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png</href>
</Icon>
<hotSpot x="20" y="2" xunits="pixels" yunits="pixels"/>
</IconStyle>
</Style>
<Folder>
<name>My Places</name>
<open>1</open>
<Style>
<ListStyle>
<listItemType>check</listItemType>
<ItemIcon>
<state>open</state>
<href>C:/Documents and Settings/sfmeyer/Local Settings/Temp/wz5b57/files/mysavedplaces_open.png</href>
</ItemIcon>
<ItemIcon>
<state>closed</state>
<href>C:/Documents and Settings/sfmeyer/Local Settings/Temp/wz5b57/files/mysavedplaces_closed.png</href>
</ItemIcon>
<bgColor>00ffffff</bgColor>
<maxSnippetLines>2</maxSnippetLines>
</ListStyle>
</Style>
<Placemark>
<name>NameRemove0</name>
<LookAt>
<longitude>-111.6385075333604</longitude>
<latitude>33.89355748553</latitude>
<altitude>0</altitude>
<heading>-0.003511129776839782</heading>
<tilt>18.73370091942461</tilt>
<range>363.2207262112541</range>
<gx:altitudeMode>relativeToSeaFloor</gx:altitudeMode>
</LookAt>
<styleUrl>#msn_ylw-pushpin</styleUrl>
<Point>
<gx:altitudeMode>clampToSeaFloor</gx:altitudeMode>
<coordinates>-111.6380073829088,33.89304257965345,0</coordinates>
</Point>
</Placemark>
</Folder>
</Document>
</kml>
错误:
File "C:\Program Files\Python26\ArcGIS10.0\lib\xml\etree\ElementTree.py", line 862, in parse
tree.parse(source, parser)
File "C:\Program Files\Python26\ArcGIS10.0\lib\xml\etree\ElementTree.py", line 587, in parse
self._root = parser.close()
File "C:\Program Files\Python26\ArcGIS10.0\lib\xml\etree\ElementTree.py", line 1254, in close
self._parser.Parse("", 1) # end of data
ExpatError: unclosed CDATA section: line 286, column 77