-1

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 code

mzjn
  • 48,958
  • 13
  • 128
  • 248
  • 1
    What have you tried so far? Please post XML as text, not as an image. – mzjn Aug 24 '22 at 13:07
  • always put code, data and full error message as text (not screenshot, not link) in question (not in comment). It will be more readable and easier to use in answer (simpler to select and copy), and more people will see it - so more people can help you. – furas Aug 24 '22 at 13:15

2 Answers2

0

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.

user3738870
  • 1,415
  • 2
  • 12
  • 24
0

If rewriting the entire file is acceptable1, 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.

julaine
  • 382
  • 3
  • 12