[英]how to change the value of element attribute in xml through python3
I have a .xml file and I want to change my latitude and longitude value from python code...so please give some idea how i do it.我有一个 .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
Your xml is not valid.您的 xml 无效。
coordi.set('longitude',self.longitude[0])
is the right way to changing attributes. 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))
Prints:印刷:
<body>
<Coordinate latitude="12.934158" longitude="228" />
<Coordinate latitude="12.934796" longitude="77.609852" />
</body>
So, all you need, is just iterate every coordinate
element and change both attributes.因此,您所需要的只是迭代每个
coordinate
元素并更改两个属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.