无法从嵌套xml

时间:2017-02-01 10:05:05

标签: python xml xml-parsing elementtree xml.etree

import xml.etree.ElementTree as ET

tree = ET.parse("D:\Parsed_CCD.xml")
doc = tree.getroot()


codeList=[]
codeSystemList=[]
codeSystemName=[]
displayName=[]
code=[]
codeS=[]
codeN=[]
display=[]
status=[]
stime=[]
etime=[]


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 elem3 in doc.findall('.//medicationsInfo/entryInfo/productCode/codeSystemName'):
    codeSystemName.append(elem3.text)

for elem4 in doc.findall('.//medicationsInfo/entryInfo/productCode/displayName'):
    displayName.append(elem4.text)  

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

for elem6 in doc.findall('.//medicationsInfo/entryInfo/productCode/translation/codeSystem'):
    codeS.append(elem6.text)    

for elem7 in doc.findall('.//medicationsInfo/entryInfo/productCode/translation/codeSystemName'):
    codeN.append(elem7.text)

for elem9 in doc.findall('.//medicationsInfo/entryInfo/productCode/translation/displayName'):
    display.append(elem9.text)  

for elem8 in doc.findall('.//medicationsInfo/entryInfo/statusCode'):
    status.append(elem8.text)

for elem10 in doc.findall('.//medicationsInfo/entryInfo/startTime'):
    stime.append(elem10.text)

for elem11 in doc.findall('.//medicationsInfo/entryInfo/endTime'):
    etime.append(elem11.text)


for i in range(len(codeList)):
    print (codeList[i],codeSystemList[i],codeSystemName[i],displayName[i],code[i],codeS[i],codeN[i],status[i],etime[i])

我需要按列打印所有值,但问题是我按列打印数据,但我无法获取所有数据,因为我有一个嵌套的xml文件,并且它具有不同数量的值。 for循环仅达到最小数量,其余数据未显示。是否可以使用不同的for循环,如i和j,并将它们追加并显示它们?

1 个答案:

答案 0 :(得分:0)

查看itertools.izip_longest函数,它将在空格中插入无,并应解决您的问题

rows=list(itertools.izip_longest(codeList,codeSystemList,codeSystemName,displayName,code,codeS,codeN,status,etime)) for row in rows: print(row)