简体   繁体   中英

Modifying element in xml using python

can anyone please explain how to modify xml element in python using elementtree.

I want to keep the rego AD-4214 and change make 'Tata' into 'Nissan' and model 'Sumo' into 'Skyline'.

xml代码

This should work:

import xml.etree.ElementTree as ET
tree = ET.parse('your_xml_source.xml')
root = tree.getroot()
root[1][1].text = "Nissan"
root[1][2].text = "Skyline"

getroot() gives you the root element ( <motorvehicle> ), [1] selects its second child, the <vehicle> with rego AD-4214. The secondary indexing, [1] and [2] , gives you AD-4214's <make> and <model> respectively. Then using the text attribute, you can change their text content.

If rewriting the entire file is acceptable 1 , the easiest way would be to turn the xml file into a dictionary (see for example here: How to convert an XML string to a dictionary? ), do your modifications on that dictionary, and convert this dict back to xml (like for example here: https://pypi.org/project/dicttoxml/ )

1 Consider lost formatting: whitespace, number formats etc may not be preserved by this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM