xml在python中使用panda读取

问题描述 投票:1回答:1

我有一个xml file.i试图以通常的方式阅读它,如下所示

def xmlfilereadread(self,path):
    doc = minidom.parse(path)
    Account = doc.getElementsByTagName("sf:ReceiverSet")[0]
    num = Account.getAttribute('totalNo')
    aList = []
    for i in range(int(num)):
        print(i)
        AccountReference = doc.getElementsByTagName("sf:Receiver")[i] 

但我需要使用熊猫不用这个代码。我可以读取data.my示例xml代码是

<?xml version="1.0" encoding="UTF-8"?>
<sf:IFile xmlns:sf="http://www.canadapost.ca/smartflow" sequenceNo="10">   
<sf:ReceiverSet documentTypes="TAXBILL" organization="lincolntax" totalNo="3">  
<sf:Receiver sequenceNo="1" correlationID="1114567890123456789">   
<sf:AccountReference>11145678901234567891111</sf:AccountReference>   
<sf:SubscriptionAuth> <sf:ParamSet>   
<sf:Param name="auth1">1114567890123456789</sf:Param>   
<sf:Param name="auth2">CARTER, JOE</sf:Param> </sf:ParamSet>   
</sf:SubscriptionAuth>  
</sf:Receiver> <sf:Receiver sequenceNo="2" correlationID="2224567890123456789">   
<sf:AccountReference>22245678901234567892222</sf:AccountReference> <sf:SubscriptionAuth> <sf:ParamSet>  
<sf:Param name="auth1">2224567890123456789</sf:Param>   
<sf:Param name="auth2">DOE, JANE</sf:Param> </sf:ParamSet>   
</sf:SubscriptionAuth> </sf:Receiver> <sf:Receiver sequenceNo="3" correlationID="3334567890123456789">   
<sf:AccountReference>33345678901234567893333</sf:AccountReference> <sf:SubscriptionAuth> <sf:ParamSet>  
<sf:Param name="auth1">3334567890123456789</sf:Param> <sf:Param name="auth2">SOZE, KEYSER</sf:Param>  
</sf:ParamSet> </sf:SubscriptionAuth> </sf:Receiver> </sf:ReceiverSet> </sf:IFile>
python xml pandas
1个回答
0
投票

XML是一种固有的分层数据格式,表示它的最自然的方式是使用树。 ET有两个类用于此目的 - ElementTree将整个XML文档表示为树,Element表示此树中的单个节点。与整个文档的交互(读取和写入文件)通常在ElementTree级别上完成。与单个XML元素及其子元素的交互在元素级别完成

.

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

或者你可以使用lxml

来自lxml import etree

root = etree.parse(r'local-path-to-.xml')
print (etree.tostring(root))
© www.soinside.com 2019 - 2024. All rights reserved.