Sashaank
Sashaank

Reputation: 964

how to change text inside tag in XML with python

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?

Upvotes: 0

Views: 745

Answers (1)

Rajith Thennakoon
Rajith Thennakoon

Reputation: 4130

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))

Upvotes: 3

Related Questions