如何在Python中递归遍历XML文件?

时间:2015-03-20 12:17:21

标签: python xml

这是我的XML文件
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>

我试图使用Element Tree解析它。我已经评论了代码部分来解释我的问题

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

我想过尝试#2
通过将整个语句放在一行中但由于未定义child_root而失败

  

文件&#34; getsccontent.py&#34;,第47行,in           对于tree_root中child_root中的child_in_child_root:       NameError:name&#39; child_root&#39;未定义

是否有比编写多个嵌套for语句更简单的方法来遍历N?

1 个答案:

答案 0 :(得分:1)

有一个单行版本,但并不简单。

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

我使用#1,因为在这种情况下不需要递归。只有当树的深度达到3时,我才会编写一个递归遍历方法。

相关问题