martin
martin

Reputation: 85

Can't find the attribute I'm looking for using Python ElementTree

enter image description hereI have an xml look like this:

<fiscalYear start="2012-01-01" end="2012-12-31">2012

<startingBalance account="1220" balance="3453871"/> see picture for more info

Now I want to find if ex an account "1220" has a startingBalance for fiscalYear 2012. The problem is that I have several fiscalYears in the xml and in the attribute "startingBalance" I have no year to look for. So in some way I have to look both in "fiscalYear" and "startingBalance", but I don't know how to do it using ElementTree.

I have tried do like this:

fiscalYear = xmltree.iter('fiscalYear')
   startingBalance = 0
   for i in fiscalYear:
          if "startingBalance" in i.attrib:
                 print("found something")
                 if i.attrib['account'] == accountNr:
                        startingBalance = i.attrib['balance']
                 else:
                        print("No startingBalance found for account:", accountNr,"year:",year )
          else:
                 print("No startingBalance found for year:",year )

but it's just print out "No startingBalance found for year" 5times (5 fiscalyears in xml)

Do someone have a clue how to fix it...? Thx

Upvotes: 0

Views: 447

Answers (1)

MikeHunter
MikeHunter

Reputation: 4304

If I'm reading your xml right, then startingBalance is not an attrib, but a tag. Change your if statement to

if "startingBalance" in i.tag:

and see if that doesn't help.

I tested you code with some xml I had here, and another problem is that your code is not getting to the subelements of fiscalYear. You have to add another line that iterates through the subelements. Something like this:

   for i in fiscalYear:
       for subele in i:   
           if "startingBalance" in subele.tag:
               print("found something")
               if subele.attrib['account'] == accountNr:
                    startingBalance = subele.attrib['balance']
                    #etc, etc

Upvotes: 1

Related Questions