Prasanna Kumar Kulkarni Prasanna Kumar Kulkarni - 4 years ago 139
Python Question

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);


In above python code, I am getting values of code and codeSystem by specifying path, but they are printing like first all codes and then all codeSystem. I want to print them parallel (like column wise), so how can I edit the above code for parsing my xml doc.

see for example I have xml in this way, I want to print code and codeSystem in column wise.

CJC CJC
Answer Source

This isn't the best way, but it should work. We scan the xml looking for code and codeSystem, trusting that they always appear in pairs (should be enforced by the xml schema).

We create two lists with the code vaules in one and codeSystem in the other, then output the lists by iterating through them to recreate the pairs.

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 This answer was updated after new information was provided in the question so the first few comments should be ignored

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download