How to add a XML element for an existing text in a XML file with python

95 views Asked by At

I have a problem with some values not being declared as XML elements in my XML files. But for further processing, I need them to be an element. Example:

<A>
    <B id="254">
        12.34
        <C>Lore</C>
        <D>9</D> 
    </B>
</A>

In the end, the XML file should look like this:

<A>
    <B id="254">
        <Z>12.34</Z>
        <C>Lore</C>
        <D>9</D> 
    </B>
</A>

The difference to stackoverflow.com/q/75586178/407651 is that in this problem an XML-Element was in front of the plain text. The feature was used in the solution. There the solution can not be used.

1

There are 1 answers

1
Timeless On

Here is one option with insert from :

from lxml import etree

tree = etree.parse("input.xml")

for b in tree.xpath("//B"):
    z = etree.Element("Z")
    z.text = b.text.strip()
    b.text = "" # <-- cut the actual value
    b.insert(0, z) # <-- paste it inside the <Z>
    
tree.write("output.xml", encoding="UTF-8", xml_declaration=True)

Output :

<?xml version="1.0" encoding="UTF-8"?>
<A>
   <B id="254">
      <Z>12.34</Z>
      <C>Lore</C>
      <D>9</D>
   </B>
</A>