如何更改 xml 到 python3 中元素属性的值

how to change the value of element attribute in xml through python3

我有一个 .xml 文件,我想从 python 代码更改我的纬度和经度值...所以请告诉我我是怎么做的。

<Coordinate latitude="12.934158" longitude="77.609316"/>
<Coordinate latitude="12.934796" longitude="77.609852"/>
doc = xml.dom.minidom.parse(verify_win.filename)

        root = doc.getroot()
        coordi = root.find('Coordinate')
        coordi.set('longitude',self.longitude[0])

# in this self.longitude[0] is a new value which i want to update in a .xml file

您的 xml 无效。 coordi.set('longitude',self.longitude[0]) 是更改属性的正确方法。

import xml.etree.ElementTree as ET

xml = """<?xml version="1.0" encoding="UTF-8"?><body>
    <Coordinate latitude="12.934158" longitude="77.609316"/>
    <Coordinate latitude="12.934796" longitude="77.609852"/></body>"""

tree = ET.fromstring(xml)
elem = tree.find('Coordinate')
elem.set("longitude", "228")

print(ET.tostring(tree))

打印:

<body>
<Coordinate latitude="12.934158" longitude="228" />
<Coordinate latitude="12.934796" longitude="77.609852" />
</body>

因此,您所需要的只是迭代每个 coordinate 元素并更改两个属性。