正在使用 elementTree 解析 xml 文档,python
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 代码中,我通过指定路径获取代码和代码系统的值,但它们的打印方式首先是所有代码,然后是所有代码系统。我想并行打印它们(如按列显示),那么如何编辑上面的代码来解析我的 xml 文档。
例如,我有 xml 这样的例子,我想按列打印代码和代码系统。
这不是最好的方法,但应该可行。我们扫描 xml 寻找 code
和 codeSystem
,相信它们总是成对出现(应该由 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])
注意此答案是在问题中提供新信息后更新的,因此应忽略前几条评论
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 代码中,我通过指定路径获取代码和代码系统的值,但它们的打印方式首先是所有代码,然后是所有代码系统。我想并行打印它们(如按列显示),那么如何编辑上面的代码来解析我的 xml 文档。
例如,我有 xml 这样的例子,我想按列打印代码和代码系统。
这不是最好的方法,但应该可行。我们扫描 xml 寻找 code
和 codeSystem
,相信它们总是成对出现(应该由 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])
注意此答案是在问题中提供新信息后更新的,因此应忽略前几条评论