繁体   English   中英

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

[英]Fetch data from xml using ElementTree in Python

我正在尝试从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

如果要递归遍历XML树中的所有元素,则应使用iter方法。 类似于以下内容的东西应该可以让您想要:

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

简单的递归函数可以实现您想要的:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM