python - 在python中使用panda读取xml
问题描述
我有一个 xml 文件。我尝试以通常的方式读取它,如下所示
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]
但我需要使用熊猫而不是这个代码。我怎样才能读取数据。我的示例 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>
解决方案
XML 是一种固有的分层数据格式,最自然的表示方式是使用树。ET 有两个用于此目的的类 - ElementTree 将整个 XML 文档表示为一棵树,而 Element 表示此树中的单个节点。与整个文档的交互(读取和写入文件)通常在 ElementTree 级别完成。与单个 XML 元素及其子元素的交互在元素级别完成
.
import xml.etree.ElementTree as ET
tree = ET.parse('country_data.xml')
root = tree.getroot()
或者你可以使用 lxml
从 lxml 导入 etree
root = etree.parse(r'local-path-to-.xml')
print (etree.tostring(root))
推荐阅读
- solr - SolrNet facets 从 Solr 返回,但不是通过 SolrNet 客户端
- css - CSS - Calc 无法使用固定位置
- sql - 如何在不中断时间的情况下结合开始日期和结束日期?
- c++ - 如何在文件中存储每通道 16 位的图像?
- javascript - 反斜杠转义在 HTML 属性中不起作用
- node.js - 如果行包含包含模式 A,则对以下行执行 smth,直到行包含模式 B 和 nodeJS
- sql-server - 如何在 SQL Server 中使用单列删除重复行
- java - 具有多个消费者的生产者使用 notify() 失败
- c# - 如何从 wpf webbrowser 获取 ckeditors 值
- swift - 当父视图的 alpha 值为 0.5 时如何使 UIView 看不到 - SWIFT