我正在尝试编辑XML文件中的一行。其中一个XML元素称为折线,包含坐标:
<location>
<street>Interstate 76 (Ohio to Valley Forge)</street>
<direction>ONE_DIRECTION</direction>
<location_description>Donegal, PA</location_description>
<polyline>40.100045 -79.202435, 40.09966 -79.20235, 40.09938 -79.20231<polyline>
</location>
我需要反转顺序并在每个坐标之间添加一个逗号,所以它写成:
<polyline>-79.202435,40.100045,-79.20235,40.09966,-79.20231,40.09938<polyline>
我可以解析文件并格式化折线元素,但不知道如何将其写回XML文件:
from xml.dom import minidom
mydoc = minidom.parse(xmlFile)
items = mydoc.getElementsByTagName('polyline')
for item in items:
newPolyline = []
lineList = item.firstChild.data.split(",")
for line in lineList:
lon = line.split(" -")[1]
lat = line.split(" -")[0]
newPolyline.append(str(lon))
newPolyline.append(str(lat))
代码可能如下所示:
from xml.dom.minidom import parseString
xmlobj = parseString('''<location>
<street>Interstate 76 (Ohio to Valley Forge)</street>
<direction>ONE_DIRECTION</direction>
<location_description>Donegal, PA</location_description>
<polyline>40.100045 -79.202435, 40.09966 -79.20235, 40.09938 -79.20231</polyline>
</location>''')
polyline = xmlobj.getElementsByTagName('polyline')[0].childNodes[0].data
xmlobj.getElementsByTagName('polyline')[0].childNodes[0].data = ','.join(
','.join(pair.split()[::-1]) for pair in polyline.split(','))
print(xmlobj.toxml())
该解决方案假设XML中只有一个polyline
标记。