Parsing name/value pairs from XML

Viewed 8876

I am trying to pull account details from XML files supplied by vendors.

I have one vendor that supplied XML files like:

<Accounts>
  <Account>
    <AccountNumber>1234567</AccountNumber>
    <Balance>$200.00</Balance>
  </Account>
  <Account>
     ...
  </Account>
</Accounts>

And I can parse this fairly easily using python:

mytree = et.parse(xml_path)
myroot = mytree.getroot()

for acc in charges_root.findall('Account'):
    acctnum = acc.find('AccountNumber').text
    balance = acc.find('Balance').text
    print(acctnum, balance)

Which outputs like this:

1234567 $200.00

However another vendor supplies the XML files in something more like name/value pairs, and I am unsure how to easily access that data. It doesn't work the same way as above:

<Accounts>
  <Account>
    <field name='AccountNumber' value='1234567' />
    <field name='Balance' value='$200.00' />
  </Account>
  <Account>
     ...
  </Account>
</Accounts>

So far I've got this, but would like to be able to access the values separately and easily:

mytree = et.parse(xml_path)
myroot = mytree.getroot()

for field in myroot.findall('Account'):
    for line in field:
        print(line.attrib)

Which outputs something like:

{'name': 'AccountNumber', 'value': '1234567'}
{'name': 'Balance', 'value': '$200.00'}

So my question is this - How can I access the values and assign them to variables (based on the name) so that I can make use of them elsewhere in the script, like I have with acctnum and balance in the first example?

4 Answers
Related