Home > Software engineering >  How to find an XML tag buried fairly deep, delete the tag if it is a match and save the XML as a str
How to find an XML tag buried fairly deep, delete the tag if it is a match and save the XML as a str

Time:12-15

Say that I have the following XML and that I am using Python. I am using xml.etree.ElementTree.

     <?xml version='1.0' encoding='UTF-8'?>
    <results preview='0'>
    <meta>
    <fieldOrder>
    <field>count</field>
    </fieldOrder>
    </meta>
        <result offset='0'>
            <field k='count'>
                <value>
                    <text1>6</text>
                    <text2>7</text>
                    <text3>8</text>
               </value>
            </field>
        </result>
    </results>

Is there an easy way for me to go down into the XML and also delete any text2 elements?

Desired result:

 <Data?xml version='1.0' encoding='UTF-8'?>
<results preview='0'>
<meta>
<fieldOrder>
<field>count</field>
</fieldOrder>
</meta>
    <result offset='0'>
        <field k='count'>
            <value>
                <text1>6</text>
                <text3>8</text>
           </value>
        </field>
    </result>
</results>

CodePudding user response:

Your sample xml is still not well formed (the opening and closing tags of the "text" children of <value> don't match.

Assuming that's fixed (that is, each closing tag matches the opening tag) the following should work:

parent = root.find('.//value[text2]')
target = parent.find('./text2')
parent.remove(target)
print(ET.tostring(doc, xml_declaration = True).decode())

The output should be your (fixed) expected output.

  • Related