gpt4 book ai didi

python - Minidom:如何检查我是否有预期的根和 child ?

转载 作者:数据小太阳 更新时间:2023-10-29 02:36:33 25 4
gpt4 key购买 nike

我有这个 xml 结构,

<root>

<child1>
</child1>
<child2>
</child2>
<child3 />
<extendedchild:name>
</extendedchild:name>

</root>

我如何检查 minidom,root 是 root,并且子元素始终是 followin 元素?

child1
child2
child3
extendedchild

我还想打印上面“子列表”中不在根目录或不在根目录的元素(outofroot, notachild):...

    <notachild />
</root>
<outofroot />

编辑:似乎 outofroot 元素被 minidom 解析器处理,它给出了 xxxxxxx.xml 有一个错误:文档元素之后的垃圾:第 12 行,第 0 列

最佳答案

您可以使用 minidom 遍历子节点并验证根节点的名称是否为 "root"。然后,您可以一次处理一个 child 并验证其他要求。

if not root.tagName == "root":
# do something
for node in root.childNodes:
# do something more

如有必要,您可以递归处理子节点。

def processChild(node):
# do some checks on node
for child in node.childNodes:
processChild(child)

关于python - Minidom:如何检查我是否有预期的根和 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12455972/

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