XML查找子标记的所有属性值

2024-09-28 03:13:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想得到每个有一个孩子的文本值和每个有一个孩子的属性值。我可以获得文本值,但我很难一个接一个地获取属性值并将每个属性值分配给一个变量

我有以下XML文件:

<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>

我有以下代码:

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

这是我第一次使用XML文件,我做了很多研究,但没有一个与我的用例相匹配。任何帮助都将不胜感激,提前感谢


Tags: text文本none属性孩子xmlfindproductid
2条回答

要获取所有<Card>标记和<Card>的每个属性/值,可以执行以下操作:

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

印刷品:

 productid 16
 PAN 64256700991593
 product MC
 programid AUST
 branchcode 

您可以访问“Card”元素的属性,如下所示:

card = cardAuthorisation.find('./Card')
for key in card.keys():
    print(key, card.get(key))

相关问题 更多 >

    热门问题