0

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.