Arunoda Gunawardana
Arunoda Gunawardana

Reputation: 77

Modifying XML in Python

What I want do do is update the values of make and model where registration_no = DE2115

XML File

<?xml version="1.0"?>
<motorvehicles>

    <vehicle> 
    <registration_no> CBB1456 </registration_no>
    <make> Toyota </make>
    <model> Premio </model>
    </vehicle>

    <vehicle>
    <registration_no> PR2245 </registration_no>
    <make> Mazda </make>
    <model> Bongo </model>
    </vehicle>

    <vehicle>
    <registration_no> DE2115 </registration_no>
    <make> TATA </make>
    <model> Sumo </model>
    </vehicle>

    <vehicle>
    <registration_no> CAR7785 </registration_no>
    <make> Kia </make>
    <model> Optima </model>
    </vehicle>

</motorvehicles>

I tried the following Code But it doesn't work.

for elm in root.findall("./vehicle/[@registraion_no='DE2115']/make"):
    elm.text="Nissan" 

Upvotes: 1

Views: 72

Answers (1)

Jack Fleeting
Jack Fleeting

Reputation: 24930

You're almost there. You can do it simply - assuming there's only one vehicle with the target registration number:

root.find('.//vehicle[registration_no=" DE2115 "]/make').text="Nissan" 

Upvotes: 1

Related Questions