簡體   English   中英

XML 查找子標簽的所有屬性值

[英]XML find all attribute values of a tag of a child

我想獲得每個孩子的文本值和每個孩子的每個屬性值。 我可以獲取文本值,但是我無法一一獲取屬性值並將每個值分配給一個變量。

我有以下 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 文件,我做了很多研究,但沒有一個符合我的用例。 任何幫助將不勝感激,提前致謝。

您可以按如下方式訪問“卡片”元素的屬性:

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

要獲得所有<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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM