gpt4 book ai didi

python - XML 查找子标签的所有属性值

转载 作者:行者123 更新时间:2023-12-04 08:54:17 24 4
gpt4 key购买 nike

我想获得每个 child 的文本值和每个 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>标签和 <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

关于python - XML 查找子标签的所有属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63919653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com