使用elementtree遍历Python中子标记的XML子标记

时间:2019-09-12 11:48:47

标签: python xml elementtree

无法遍历子标记中的子标记

试图通过root.iter()查找所有子标记,并对其进行迭代。 但是输出不是在标记的层次结构中生成的

for child in root.iter():
    child_tag = child.tag

    for child in root.findall('.//' + child_tag):          
        txt = "tag1/" + "tag2/" + str(child_tag) + "/" + str(child)
        print(txt)

预期输出:

tag1
tag1/tag2
tag1/tag2/tag3
tag1/tag2/tag3/tag4
tag1/tag2/tag3/tag5
tag1/tag2/tag3/tag5/tag6

xml文件详细信息:

<tag1>
    <tag2>
        <tag3>
                <tag4>         </tag4>
                <tag5>  
                    <tag6>        </tag6>      
                </tag5>
        </tag3>
    </tag2>
</tag1>

收到的输出:

tag1
tag1/tag2
tag1/tag2/tag3
tag1/tag2/tag3/tag4
tag1/tag2/tag3/tag5
tag1/tag2/tag5/tag6

---不是按照等级

1 个答案:

答案 0 :(得分:2)

列出[Python 3.Docs]: xml.etree.ElementTree - The ElementTree XML API

硬编码节点标签(“ tag1” “ tag2” :为什么只有那些标签而不是其他标签?)表明(严重)错误。
这是一个简单的变体,可递归处理每个 XML 节点。

code00.py

#!/usr/bin/env python3

import sys
from xml.etree import ElementTree as ET


def iterate(node, path=""):
    if path:
        current_path = path + "/" + node.tag
    else:
        current_path = node.tag
    print("{0:s}".format(current_path))
    for child in node:
        iterate(child, path=current_path)


def main():
    xml_file_name = "./file00.xml"
    tree = ET.parse(xml_file_name)
    root = tree.getroot()
    iterate(root)


if __name__ == "__main__":
    print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
    main()
    print("\nDone.")

输出

[cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q057906081]> "e:\Work\Dev\VEnvs\py_064_03.07.03_test0\Scripts\python.exe" code00.py
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] 64bit on win32

tag1
tag1/tag2
tag1/tag2/tag3
tag1/tag2/tag3/tag4
tag1/tag2/tag3/tag5
tag1/tag2/tag3/tag5/tag6

Done.
相关问题