如何使用 Python 编辑 XML 文件

How to edit an XML file using Python

我正在尝试编辑 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 标签。