使用elementTree、python解析xml文档

2024-04-24 19:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

import xml.etree.ElementTree as ET

tree = ET.parse("Parsed.xml")
doc = tree.getroot()

for elem in doc.findall('.//medicationsInfo/entryInfo/productCode/code'):
    print (elem.text);

for elem in doc.findall('.//medicationsInfo/entryInfo/productCode/codeSystem'):
    print (elem.text);  

在上面的python代码中,我通过指定path来获取code和codeSystem的值,但它们的打印方式是先打印所有代码,然后打印所有codeSystem。我想并行地打印它们(比如按列),所以如何编辑上面的代码来解析我的xml文档。你知道吗

例如,我有这样的xml,我想按列方式打印代码和codeSystem。你知道吗


Tags: 代码intreefordoccodexmlet
1条回答
网友
1楼 · 发布于 2024-04-24 19:56:48

这不是最好的办法,但应该行得通。我们扫描xml寻找codecodeSystem,相信它们总是成对出现(应该由xml模式强制执行)。你知道吗

我们创建两个列表,其中一个是code变量,另一个是codeSystem,然后通过遍历列表来重新创建对,从而输出列表。你知道吗

codeList=[]
codeSystemList=[]

for elem1 in doc.findall('.//medicationsInfo/entryInfo/productCode/code'):
    codeList.append(elem1.text)

for elem2 in doc.findall('.//medicationsInfo/entryInfo/productCode/codeSystem'):
    codeSystemList.append(elem2.text)


for i in range(len(codeList)):
    print(codeList[i],codeSystemList[i])

NB在问题中提供了新信息后,此答案被更新,因此前几条评论应被忽略

相关问题 更多 >