xml - ElementTree Python:如果兄弟姐妹嵌套,如何提取兄弟姐妹?
问题描述
我有一个要转换为 Excel 数据集的 XML 文件。XML 的排列方式如下:
<XML Data>
<Record>
<ID>
<Client id="01"></Client>
</ID>
<Service>
<Product id="A"></Product>
<Product id="B"></Product>
<Product id="C"></Product>
</Service>
</Record>
<Record>
<ID>
<Client id="02"></Client>
</ID>
<Service>
<Product id="A"></Product>
<Product id="B"></Product>
<Product id="Y"></Product>
</Service>
</Record>
<Record>
<ID>
<Client id="24"></Client>
</ID>
<Service>
<Product id="U"></Product>
</Service>
</Record>
</XML Data>
如您所见,每条记录都显示了具有多个服务的单个客户端。
我正在尝试仅使用 ElementTree 来完成这项工作。这是为每个客户端 ID 返回所有服务的错误代码——我无法弄清楚如何让它返回客户端实际拥有的每个服务:
for x in root.findall("Record/ID/Client"):
client = x.get("id")
for y in root.findall('.//Service/Product'):
service = y.get("id")
print(client, service)
我正在尝试以 CSV 格式将其安排为:
ClientID ServiceID
01 A
01 B
01 C
02 A
02 B
02 Y
24 U
任何建议将不胜感激!我已经查找了这个,但只能找到显示如何提取实际兄弟姐妹的资源——因为客户端 ID 和服务 ID 是我想要提取的孩子的父母,这被证明有点令人困惑。谢谢!
解决方案
与其先选择Client
,不如先选择Record
。
然后你的第二个 for 循环可以从root.finall
to更改为x.findall
只会找到Product
current 的元素Record
。
例子...
XML 输入(test.xml;修复了无效的根元素)
<XML_Data>
<Record>
<ID>
<Client id="01"></Client>
</ID>
<Service>
<Product id="A"></Product>
<Product id="B"></Product>
<Product id="C"></Product>
</Service>
</Record>
<Record>
<ID>
<Client id="02"></Client>
</ID>
<Service>
<Product id="A"></Product>
<Product id="B"></Product>
<Product id="Y"></Product>
</Service>
</Record>
<Record>
<ID>
<Client id="24"></Client>
</ID>
<Service>
<Product id="U"></Product>
</Service>
</Record>
</XML_Data>
Python
import xml.etree.ElementTree as ET
tree = ET.parse('test.xml')
root = tree.getroot()
for x in root.findall("Record"):
client = x.find("ID/Client").get("id")
for y in x.findall('.//Service/Product'):
service = y.get("id")
print(client, service)
打印输出
01 A
01 B
01 C
02 A
02 B
02 Y
24 U
推荐阅读
- php - Laravel 对数字不起作用的最小长度验证
- c# - 使用单个用户登录到应用程序服务器上的 SQL Server
- uibutton - UIButton 的 IBDesignable,IBInspectable 变量为零
- javascript - 如何使用javascript创建程序来计算串联电阻?
- linux - 当 Linux 操作系统无法正常关闭/重置时,如何防止文件/磁盘损坏?
- javascript - script-src 包含无效的源:''wasm-eval' 在使用 web worker 时
- botframework - LUIS 离线支持
- laravel - 我的页面是否会被谷歌抓取,因为它们是异步解释并注入 DOM 的 Markdown 文件?
- mongodb - 如何通过检查mongodb和spring条件中的数组元素来选择文档
- java - 如何在运行时更改 API Base Url(Retrofit、Android、Java)?