0

This is my XML File
temp_student.xml

<?xml version='1.0' encoding='UTF-8'?>
 <studentinformation doc_version='2.0'>
  <student>
   <rollno>1</rollno>
   <name>ABC</name>
   <age>22</age>
   <gender>MALE</gender>
  </student>
    <student>
   <rollno>2</rollno>
   <name>DEF</name>
   <age>56</age>
   <gender>MALE</gender>
  </student>
 </studentinformation>

I'm trying to parse it using Element Tree. I've commented the section of the code to explain my problem

import subprocess,re,os,time,shutil,glob
import sys
from sys import stdout
from subprocess import STDOUT
from _winapi import NULL
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import Element, SubElement
from logging import root

xmlfile='temp_student.xml'
xml_tree = ET.parse(xmlfile)
tree_root = xml_tree.getroot()
print('Root Tag is '+str(tree_root.tag))
print('Root Attrib is '+str(tree_root.attrib))
print('Printing the children from root ')
# 1 for child_root in tree_root:
#     for child_in in child_root:
         # perform some operation
# 2 for child_in in child_root in tree_root:
         # perform some operation

I thought of trying #2
by putting the entire statement in a single line but it fails because child_root is NOT defined

File "getsccontent.py", line 47, in for child_in_child_root in child_root in tree_root: NameError: name 'child_root' is not defined

Is there any simpler way than writing multiple nested for statements to traverse N ?

1 Answer 1

1

There is a single-line version but it's not simpler.

for child in [child for child_root in tree_root for child in child_root]:
    print(child)

I'd use #1 because there's no need for recursion in this case. Only when depth of the tree reaches 3 I'll write a recursive traversing method.

Sign up to request clarification or add additional context in comments.

2 Comments

can you please explain the logic ? Is this a list comprehension ? If Yes, a brief explanation of how it works might be useful
@DhiwakarRavikumar This is list comprehension. A simpler example: [(x, y) for x in range(1, 5) for y in range(0, x)], where (x, y) is the output expression, for x in range(1, 5) and for y in range(0, x) are the two input expressions that defines the input list. Note that the second input expression can depend on the first expression.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.