如何使用Python编辑XML文件

时间:2018-09-17 14:51:41

标签: python xml elementtree

我正在尝试在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))

1 个答案:

答案 0 :(得分:1)

代码可能看起来像这样:

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标签。