Prashant Kumar
Prashant Kumar

Reputation: 13

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.

<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

Upvotes: 1

Views: 68

Answers (1)

Ilya Datskevich
Ilya Datskevich

Reputation: 71

Your xml is not valid. coordi.set('longitude',self.longitude[0]) is the right way to changing attributes.

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.

Upvotes: 1

Related Questions