0

I have multiple XML files in a folder. all the XML files have a folder tag in them. this is a sample XML file

<root>
  ...
  <folder>./dir_us/</folder>
  <filename>file1.txt</filename>
  ...
</root>

I want to open every XML file and change the contents of the folder tag to ./root_folder/

I am able to open the XML file and I am able to read the contents inside the <folder> tag. But I am not able to change the text to ./root_folder/

This is my code so far

import os
import xml.etree.cElementTree as ET

dir = './XML_FOLDER/'

for file in os.listdir(dir):

    tree = ET.parse(os.path.join(dir, file))
    root_xml = tree.getroot()

    for folder in root_xml.findall('folder'):
        folder.text = './root_folder/'

What am I doing wrong?

1 Answer 1

3

you should write the changed object to file.Try this

import os
import xml.etree.cElementTree as ET

dir = './XML_FOLDER/'

for file in os.listdir(dir):

    tree = ET.parse(os.path.join(dir, file))
    root_xml = tree.getroot()

    for folder in root_xml.findall('folder'):
        folder.text = './root_folder/'
    tree.write(os.path.join(dir, file))
Sign up to request clarification or add additional context in comments.

2 Comments

understood. I have to write the updated text into the file. works now. thanks
yah.you should overwrite the same file by saving the updated object.happy coding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.