Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to edit xml root attributes with python

Recently ive been messing around with editing xml files with a python script for a project im working on but i cant figure out how to edit the attributes of the root element.

for example the xml file would say:

<root width="200">
  <element1>
  </element1>
</root>

what i want to do is have my code find the width attribute and change it to some other value, i know how to edit elements after the root but not the root itself

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

code im using for changing attributes

>Solution :

You could use the following module xml.etree.ElementTree. With this module you can set up attributes using xml.etree.ElementTree.Element.set()
Here is an example of snippet you could use:

import xml.etree.ElementTree as ET

tree = ET.parse('input.xml')
root = tree.getroot()
root.set('width','400')
print(root.attrib)

tree.write('output.xml')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading