How to make changes in XML file in Python

Question:

I have a xml file

MC.xml contents of which are

<?xml version="1.0" encoding="UTF-8"?>
<MCOO type="list">

    <AAA>
        <Active value="True" li="True" mv="True"/>
        <Plot value="True" li="False" mv="False"/>
        <Color value="#990000"/>

    </AAA>

    <BBB>
        <Active value="True" li="True" mvl="True"/>
        <Plot value="True" li="False" mvl="False"/>
        <Color value="#990000"/>


    </BBB>

    <CCC>
        <Active value="True" li="False" mv="True"/>
        <Plot value="False" li="False" mv="False"/>
        <Color value="#990000"/>

    </CCC>
    
</MCOO>

I have a list lets say

kk = [‘AAA’, ‘CCC’]

So i want to change the Active value, part to True/False if the element is in the list.

I checked out some videos but was not able to parse the contents properly to access the Active values. can someone help.

Answers:

You can use the xml.etree.ElementTree module (documentation: https://docs.python.org/3/library/xml.etree.elementtree.html) to parse and modify your XML file.

If you want to change the active value to True if the element is in the list and false if it is not in the list then you can use this code:

import xml.etree.ElementTree as ET

kk = ['AAA', 'CCC']

# Parse the XML file
tree = ET.parse('MC.xml')
root = tree.getroot()

# Iterate over the elements in the XML and update the 'Active' attribute
for child in root:
    if child.tag in kk:
        child.find('Active').set('value', 'True')
    else:
        child.find('Active').set('value', 'False')

See documentation for more info about finding and setting and so on. If you want to change the original file then you can use the following code:

tree.write('MC.xml', encoding='UTF-8', xml_declaration=True)

if you want to write to a nerw file then just change the name

Answered By: Johan Abdullah Holm
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.