Skip to content Skip to sidebar Skip to footer

Python Write Siblings In Xml Below Desired Tag

I am trying to add some sibling tags after 10 tag My XML looks like: 999

Solution 1:

You can find position of VIDPOM in list of children of SLUCH

index = list(SLUCH).index(VIDPOM)  # deprecated: SLUCH.getchildren().index(VIDPOM)

and then you can insert one position after VIDPOM

SLUCH.insert(index+1, new_tag)

To format new element like VIDPOM (the same indentations) you can copy tail

new_tag.tail = VIDPOM.tail

Minimal working code - with data directly in code.

text ='''
<ZAP>
    <N_ZAP>999</N_ZAP>
    <SLUCH>
      <IDCASE>100100100</IDCASE>
      <USL_OK>3</USL_OK>
      <VIDPOM>10</VIDPOM>
      <IDSP>99</IDSP>
      <USL>
        <IDSERV>123456789</IDSERV>
        <DATE_IN>2020-12-01</DATE_IN>
      </USL>
    </SLUCH>
</ZAP>
'''import xml.etree.ElementTree as ET

#tree = ET.parse('file.xml')#root = tree.getroot()
root = ET.fromstring(text)

for SLUCH in root.iter('SLUCH'):
    VIDPOM = SLUCH.find('VIDPOM')

    new_tag = ET.Element('MY_CUSTOM_TAG')
    new_tag.text = 'TEXT IS HERE'
    new_tag.tail = VIDPOM.tail  # copy text after `tag`

    index = list(SLUCH).index(VIDPOM)
    #index = SLUCH.getchildren().index(VIDPOM)  # deprecated
    SLUCH.insert(index+1, new_tag)

print(ET.tostring(root).decode())

Result:

<ZAP><N_ZAP>999</N_ZAP><SLUCH><IDCASE>100100100</IDCASE><USL_OK>3</USL_OK><VIDPOM>10</VIDPOM><MY_CUSTOM_TAG>TEXT IS HERE</MY_CUSTOM_TAG><IDSP>99</IDSP><USL><IDSERV>123456789</IDSERV><DATE_IN>2020-12-01</DATE_IN></USL></SLUCH></ZAP>

Post a Comment for "Python Write Siblings In Xml Below Desired Tag"