我有一个XML文件,我正尝试将其转换为Excel数据集。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是我要提取的子项的父项,所以事实证明这有点令人困惑。谢谢!
发布于 2019-04-08 08:28:19
首先选择Record
,而不是首先选择Client
。
然后,您的第二个for循环可以从root.finall
更改为x.findall
,它将只查找当前Record
的Product
元素。
例如。
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
https://stackoverflow.com/questions/55564681
复制相似问题