[英]How to recursively traverse an XML File in Python?
這是我的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>
我正在嘗試使用元素樹來解析它。 我評論了代碼部分以解釋我的問題
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而失敗
tree_root中child_root中child_in_child_root的文件“ getsccontent.py”,第47行:NameError:未定義名稱“ child_root”
有沒有比編寫多個嵌套的遍歷N語句更簡單的方法?
有單行版本,但並不簡單。
for child in [child for child_root in tree_root for child in child_root]:
print(child)
我將使用#1,因為在這種情況下無需遞歸。 只有當樹的深度達到3時,我才會編寫一種遞歸遍歷方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.