Sekar Ramu
Sekar Ramu

Reputation: 483

Finding XML tags and inserting new tags in particular position in Python3 using xml.etree.ElementTree

I have an example file of following format.

Source XML data:

<nametag dummy1 ="YES" dummy2 ="PASS THROUGH" >
            <PARTITION DESCRIPTION ="" NAME ="Partition #1"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #2"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #3"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #4"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #5"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #6"/>

</nametag>

Target:

<nametag dummy1 ="YES" dummy2 ="PASS THROUGH" >
            <PARTITION DESCRIPTION ="" NAME ="Partition #1"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #2"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #3"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #4"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #5"/>
            <PARTITION DESCRIPTION ="" NAME ="Partition #6"/>
<newtag value=1 value=2/>
</nametag>

I am able to pass thru the entire document and find the and even able to pass thru the tags. My requirement is to find the last tag and add a new tag element as mentioned in Target xml given above. No of line items is not always same so looping thru with the fixed iteration won't work.

I will have to find the last tag and insert "" after that.

Need to find if its the last tag. I am able to parse thru the xml file using code similar to the below one.

import xml.etree.ElementTree as ET
tree = ET.parse('some.xml')
root = tree.getroot()
for partition in root.iter('PARTITION'):
    partitiondetail = partition.get('NAME')
    if partitiondetail == 'somepattern':
        print(partitiondetail)

Upvotes: 0

Views: 942

Answers (1)

Sekar Ramu
Sekar Ramu

Reputation: 483

This fixed my issue.

for element in root.iter('nametag'):
    new_subelement = ET.Element("newtag", value1 ="1", value2="2")
    element.append(new_subelement)

tree.write('output.xml')

This will write the required xml data in a new file.

Upvotes: 1

Related Questions