【问题标题】:Iterate through XML child of child tags in Python using elementtree使用 elementtree 在 Python 中遍历子标签的 XML 子代
【发布时间】:2019-09-12 11:48:47
【问题描述】:

无法遍历子标签内的子标签

尝试通过 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

--- 不按层次结构

【问题讨论】:

  • 如果您查看打印语句,您只有 4 个标签名称的空间:tag1、tag2、str(child_tag)、str(child)。因此,您的最后一次打印将无法拥有您想要的 5 个层次结构。您需要存储当前迭代元素的祖父元素并在 tag1/tag2 之后输出这些元素。

标签: python xml elementtree


【解决方案1】:

上市[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.

【讨论】:

  • 谢谢.....前两个标签的硬编码是因为所有节点都存在。我现在将删除硬编码。
  • 一个后续问题——如何将输出添加到数据框?
  • 嗯,我不知道。我不知道数据框的结构和其他此类细节。不过你可以问另一个问题。
猜你喜欢
  • 1970-01-01
  • 2020-08-07
  • 2016-09-17
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
相关资源
最近更新 更多