Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make changes in XML file in Python

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading