gpt4 book ai didi

python - 使用 elementtree 在 Python 中迭代子标签的 XML 子代

转载 作者:行者123 更新时间:2023-12-01 00:34:34 25 4
gpt4 key购买 nike

无法迭代子标签内的子标签

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

--- 不按层次结构

最佳答案

列表[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.

关于python - 使用 elementtree 在 Python 中迭代子标签的 XML 子代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57906081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com