Home > front end >  how to edit xml root attributes with python
how to edit xml root attributes with python

Time:04-13

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

code im using for changing attributes

CodePudding user response:

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')
  • Related