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

Question:

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">
        <C>Lore</C>
        <D>9</D> 
        12.34
    </B>
    <B id="255">
        <C>Ipsum</C>
        <D>125</D> 
        23.45
    </B>
    <E/>
    <F id="256">
        <G>Lore Ipsum
            <E>79</E> 
            34.56
        </G>
    </F>
</A>

In the end, the XML file should look similar to this:

<A>
    <B id="254">
        <C>Lore</C>
        <D>9</D> 
        <Z>12.34</Z> 
    </B>
    <B id="255">
        <C>Ipsum</C>
        <D>125</D> 
        <Z>23.45</Z>
    </B>
    <E/>
    <F id="256">
        <G>Lore Ipsum
            <E>79</E>
            <Y>34.56</Y> 
        </G>
    </F>
</A>

I looked in various python documentation but only found a way to add a new element with a value.

Asked By: JME

||

Answers:

You can do this with the build in xml.etree.ElementTree:

import xml.etree.ElementTree as ET

tree = ET.parse('Start.xml')
root = tree.getroot()

# Show current XML
ET.dump(root)

# catch the tail value
for elem in root.iter():
    tail_text = elem.tail

# reset the tail value
for elem in root.iter():
    if elem.tag =="C":
        elem.tail = 'n'

# define new node
ET.SubElement(root, "D")

# assign the new nodes text
for elem in root.iter():
    if elem.tag == "D":
        elem.text = tail_text

# Show changed XML        
ET.dump(root)

# write the changed tree to a file
tree.write("new.xml", encoding='utf-8', xml_declaration=True)
Answered By: Hermann12