Adding attributes with ascending integer values to XML elements

Question:

I want to add the add attribute ‘id="number"’ to an existing file. But the number should be ascending in the way they are added.
So right now my XML file looks like this:

<Invoice>  
    <Fussteil>
       <Summen>
            <QF/>
            <UstSatz>21.00</UstSatz>
            <Betrag>
                <Bezeichnung>Steuerbetrag</Bezeichnung>
                <QF>124</QF>
                <Wert>8.8</Wert>
            </Betrag>
            <Betrag>
                <Bezeichnung>steuerpflichtiger Betrag</Bezeichnung>
                <QF>125</QF>
                <Wert>41.9</Wert>
            </Betrag>
        </Summen>
        <Betrag>
            <Bezeichnung>Gesamtbetrag alle Zu/Abschläge</Bezeichnung>
            <QF>131</QF>
            <Wert>12.5</Wert>
        </Betrag>
        <Betrag>
            <Bezeichnung>Gesamter Gebuehrenbetrag</Bezeichnung>
            <QF>176</QF>
            <Wert>8.8</Wert>
        </Betrag>
    </Fussteil>  
</Invoice>  

And in the end it should look like this:

<Invoice>  
    <Fussteil id="0" >
       <Summen id="1">
            <QF/>
            <UstSatz>21.00</UstSatz>
            <Betrag id="2">
                <Bezeichnung>Steuerbetrag</Bezeichnung>
                <QF>124</QF>
                <Wert>8.8</Wert>
            </Betrag>
            <Betrag id="3">
                <Bezeichnung>steuerpflichtiger Betrag</Bezeichnung>
                <QF>125</QF>
                <Wert>41.9</Wert>
            </Betrag>
        </Summen>
        <Betrag id="4">
            <Bezeichnung>Gesamtbetrag alle Zu/Abschläge</Bezeichnung>
            <QF>131</QF>
            <Wert>12.5</Wert>
        </Betrag>
        <Betrag id="5">
            <Bezeichnung>Gesamter Gebuehrenbetrag</Bezeichnung>
            <QF>176</QF>
            <Wert>8.8</Wert>
        </Betrag>
    </Fussteil>  
<Invoice>   

I have tried to do it with python:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml') 
root = tree.getroot()


def add_ID(root):
    for child in root:
        child.set('id', 'some value')
        print(child.tag, child.attrib)
        add_ID(child)

add_ID(root)    
     
tree.write('output.xml')

But then I can only use one fixed value for the attribute ‘id="some value"’

Asked By: JME

||

Answers:

Here is one way to get the wanted output.

import xml.etree.ElementTree as ET

tree = ET.parse('file.xml')

val = 0

for elem in tree.iter():
    if elem.tag in ["Fussteil", "Summen", "Betrag"]:
        elem.set("id", str(val))
        val += 1 

tree.write('output.xml')
Answered By: mzjn