Home > Enterprise >  How to insert elements into a multiple nested XML?
How to insert elements into a multiple nested XML?

Time:07-29

I have an XML in the following form:

<PROJECT>
    <UPDATE_TYPE>FULL</UPDATE_TYPE>
    <PROJECT_NAME>GEN20x_BALBOA</PROJECT_NAME>
    <BLOCK>
        <BLOCK1>
            <TYPE>BOOT</TYPE>
            <TASK>
                <INSTALL_OPTIONS softwareType="aaa" />
                <INSTALL_OPTIONS softwareType="qqq" />
            </TASK>
            <TASK>
                <INSTALL_OPTIONS softwareType="mno" />
                <INSTALL_OPTIONS softwareType="xzy" />
            </TASK>
            <TASK>
                <INSTALL_OPTIONS softwareType="rrr" />
                <INSTALL_OPTIONS softwareType="uuu" />
            </TASK>
        </BLOCK1>
    </BLOCK>
</PROJECT>

I need to insert another <INSTALL_OPTIONS> inside all the TASK tags, the result thus should look like this:

        <BLOCK1>
            <TYPE>BOOT</TYPE>
            <TYPE>BOOT</TYPE>
            <TASK>
                <INSTALL_OPTIONS softwareType="aaa" />
                <INSTALL_OPTIONS softwareType="qqq" />
        
                <INSTALL_OPTIONS softwareType="new"/>
            </TASK>
            <TASK>
                <INSTALL_OPTIONS softwareType="mno" />
                <INSTALL_OPTIONS softwareType="xzy" />
        
                <INSTALL_OPTIONS softwareType="new"/>
            </TASK>
            <TASK>
                <INSTALL_OPTIONS softwareType="rrr" />
                <INSTALL_OPTIONS softwareType="uuu" />
        
                <INSTALL_OPTIONS softwareType="new"/>
            </TASK>
        </BLOCK1>

I tried the below approach but was able to insert only to the first tag:

task = root.find('.//TASK')
io = ET.SubElement(task, 'INSTALL_OPTIONS')
io.attrib['softwareType'] = 'new'

How to get it inserted at all the 3 places?

CodePudding user response:

You need to use the insert() method. Assuming each Task has exactly two INSTALL_OPTIONS, Try something like this:

tasks = root.findall('.//TASK')
new_io= ET.fromstring('<INSTALL_OPTIONS softwareType="new"/>')
for task in tasks:
    task.insert(2,new_io)
print(ET.tostring(doc).decode())

Output should be your expected output.

  • Related