-1

I have this simple .xml file

<info>
    <fullname name="C:\TEST\999" />
    <Additionalinfo>
      <folder name="C:\TEST\111" />
      <folder name="C:\TEST\222" />
    </Additionalinfo>
</info>

I need to read the attribute of fullname (C:\TEST\999) and if exists also all the attributes of Additionalinfo ( C:\TEST\111 and C:\TEST\222 ) do some changes to their values and save the .xml with the changes.
I'm new with python and .xml, for now I just managed to print these attributes.
How can I update it ?

import xml.etree.ElementTree as ET

tree = ET.parse('C:\\test.xml')
root = tree.getroot()

for fullname in root.iter('fullname'):
    print(fullname.attrib)
for folder in root.iter('folder'):
    print(folder.attrib)

tree.write('C:\\test.xml')
0

1 Answer 1

0

You might use .set method as follows

import xml.etree.ElementTree as ET

tree = ET.parse('C:\\test.xml')
root = tree.getroot()

for fullname in root.iter('fullname'):
    fullname.set('name','newvalue')

tree.write('C:\\test_changed.xml') # do not overwrite existing file until you are sure you get effect exactly as needed

which creates file with content as follows

<info>
    <fullname name="newvalue" />
    <Additionalinfo>
      <folder name="C:\TEST\111" />
      <folder name="C:\TEST\222" />
    </Additionalinfo>
</info>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.