2

I want to get the text value of every child that has one and every attribute value of every child that has one. I can get the text values but I am having trouble getting the attribute values one by one and assigning each to a variable.

I have the following XML file:

<Transactions>
  <CardAuthorisation xmlns:xsi="http://...">
    <RecType>ADV</RecType>
    <AuthId>60874046</AuthId>
    <LocalDate>202008010000</LocalDate>
    <SettlementDate>202008</SettlementDate>
    <Card productid="16" PAN="64256700991593" product="MC" programid="AUST" branchcode="" />
  </CardAuthorisation>
</Transactions>

I have the following code:

import xml.etree.ElementTree as et 
xFile = "test.XML"
xtree = et.parse(xFile)
xRoot = xtree.getroot()
for cardAuthorisation in xRoot.findall('CardAuthorisation'):
    recType = cardAuthorisation.find('./RecType').text
    authId = cardAuthorisation.find('./AuthId').text
    localDate = cardAuthorisation.find('./LocalDate').text
    settlementDate = cardAuthorisation.find('./SettlementDate').text
    #here is where I am having trouble with
    #pseudocode
    for every attribute in Card:
       card_productid = #the value of productid if not None else None
        .
        .
        .
       branchcode = #the value of branchcode if not None else None

This is my first time working with XML files, I have done a lot of research but none of them matches my use case. Any help would be highly appreciated, thanks in advance.

Green Green
  • 43
  • 1
  • 8

2 Answers2

1

You can access attributes of the "Card" element as follows:

card = cardAuthorisation.find('./Card')
for key in card.keys():
    print(key, card.get(key))
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27
  • thank you so much @Alexandra Dudkina, both of your answers solve the problem, you have saved me so much time :). I had no solution now I have two, please choose it between you two if I shall give the check mark by FIFO standard or if I should help an uprising stackoverflow member :). Thanks again! – Green Green Sep 16 '20 at 13:07
1

To get all <Card> tags and each attribute/value of <Card>, you can do:

for c in cardAuthorisation.findall('Card'):
    for k, v in c.items():
        print(k, v)

Prints:

 productid 16
 PAN 64256700991593
 product MC
 programid AUST
 branchcode 
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • thank you so much @Andrej Kesely, both of your answers solve the problem, you have saved me so much time :). I had no solution now I have two, please choose it between you two if I shall give the check mark by FIFO standard or if I should help an uprising stackoverflow member :). Thanks again! – Green Green Sep 16 '20 at 13:07