gpt4 book ai didi

python - 在 Python 中使用 ElementTree 从 xml 中获取数据

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:02 26 4
gpt4 key购买 nike

我正在尝试从 xml 文件中提取一些数据。下面给出了 xml 的外观。

<?xml version="1.0" encoding="UTF-8"?>
<Stores>
<Store>
<Action>new</Action>
<StoreID>1001</StoreID>
<EmpID/>
<Agent>
<Name/>
<EmpName>Scott</EmpName>
</Name>
<BillData>
<BillInfo>
<Action>new</Action>
<CustName></CustName>
<BillNumber>3343</BillNumber>
</BillInfo>
</BillData>
</Store>
</Stores>

我正在尝试从上述数据集中获取每一列及其数据。以下是我到目前为止所取得的成就:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
for elem in root:
for subelem in elem:
print(subelem.tag)
print(subelem.text)

输出如下:

Action
new
StoreID
1001
Agent


BillData

我正在尝试提取子级别的数据。谁能建议我如何提取存储在“BillInfo”下的数据

Action
new
CustName
BillNumber
3343

最佳答案

简单的递归函数,实现你想要的:

import xml.etree.ElementTree as ET
tree = ET.parse('file.xml')
root = tree.getroot()
search(root)

def search(elem):
for e in elem:
print(e.tag)
print(e.text)
search(e)

关于python - 在 Python 中使用 ElementTree 从 xml 中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53500634/

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