1

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.

JME
  • 27
  • 4
  • 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. – JME Apr 13 '23 at 11:43

1 Answers1

0

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>
Timeless
  • 22,580
  • 4
  • 12
  • 30