我有一个 .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>
因此,您所需要的只是迭代每个坐标
元素并更改这两个属性。
关于python - 如何通过python3改变xml中元素属性的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57668627/