繁体   English   中英

使用elementTree,python解析xml文档

[英]parsing xml document using elementTree, 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代码中,我通过指定路径获取代码和codeSystem的值,但它们首先打印所有代码然后打印所有codeSystem。 我想并行打印它们(如列方式),那么如何编辑上面的代码来解析我的xml doc。

例如,我看到我有这种方式的xml,我想按列打印代码和codeSystem。

这不是最好的方法,但应该有效。 我们扫描xml寻找codecodeSystem ,相信它们总是成对出现(应该由xml架构强制执行)。

我们创建两个列表,其中一个code vaules,另一个为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])

注意:在问题中提供新信息后,此答案已更新,因此应忽略前几条评论

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM