Python-如何确定已解析的XML元素的层次结构级别? [英] Python - How to determine hierarchy level of parsed XML elements?

查看:486
本文介绍了Python-如何确定已解析的XML元素的层次结构级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python从XML文件中解析带有特定标签的元素,并生成输出excel文档,该文档将包含元素并保留其层次结构.

I am trying to parse elements with certain tag from XML file with Python and generate output excel document, which would contain elements and also preserve their hierarchy.

我的问题是我无法弄清楚每个元素(在哪个解析器上进行迭代)嵌套的深度.

My problem is that I cannot figure out how deeply nested each element (over which parser iterates) is.

XML示例摘录(3个元素,它们可以在其内部任意嵌套):

XML sample extract (3 elements, they can be nested arbitrarily within themselves):

<A>
   <B>
      <C>
      </C>
   </B>
</A>
<B>
    <A>
    </A>
</B>

以下使用ElementTree的代码很好地遍历了元素.但是我认为ElementTree无法确定每个元素嵌套的深度.见下文:

Following code, using ElementTree, worked well to iterate over elements. But I think ElementTree is not capable determining how deeply each element is nested. See below:

import xml.etree.ElementTree as ET

root = ET.parse('XML_file.xml')
tree = root.getroot()
for element in tree.iter():
    if element.tag in ("A","B","C"):
        print(element.tag)

这将使我以正确的顺序获取元素A,B,C的列表.但是我需要打印出它们的水平信息,

This will get me the list of elements A,B,C in right order. But I need to print them out with information of their level,

不仅如此:

A
B
C
B
A

但是类似:

A
--B
----C
B
--A

要执行此操作,我需要获取每个元素的级别.是否有适用于python的合适解析器,可以轻松地做到这一点?我会想象像"element.hierarchyLevel"之类的东西会返回一些Integer索引...

To be able to do this, I need to get the level of each element. Is there any suitable parser for python which can easily do this? I would imagine something like "element.hierarchyLevel" which would return some Integer index...

推荐答案

尝试使用递归函数来跟踪您的级别".

Try using a recursive function, that keeps track of your "level".

import xml.etree.ElementTree as ET

def perf_func(elem, func, level=0):
    func(elem,level)
    for child in elem.getchildren():
        perf_func(child, func, level+1)

def print_level(elem,level):
    print '-'*level+elem.tag

root = ET.parse('XML_file.xml')
perf_func(root.getroot(), print_level)

这篇关于Python-如何确定已解析的XML元素的层次结构级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆