0

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.

JME
  • 27
  • 4

1 Answers1

0

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)
Hermann12
  • 1,709
  • 2
  • 5
  • 14
  • Thanks for your answer. That works for the XML File above. What if there is more than one nested element? I have updated the XML file in the problem description. – JME Feb 27 '23 at 21:58
  • If you change your question after the answer you should open another question. The doing is the same you can loop over the whole tree. Please accept my answer to your first question. Thanks. – Hermann12 Feb 27 '23 at 22:18