【问题标题】:How to check if an xml node has children in python with minidom?如何检查xml节点是否在带有minidom的python中有子节点?
【发布时间】:2013-07-12 19:11:48
【问题描述】:

如何用minidom检查xml节点是否有python中的子节点?

我正在编写一个递归函数来删除 xml 文件中的所有属性,我需要在再次调用相同的函数之前检查一个节点是否有子节点。

我尝试过的: 我尝试使用 node.childNodes.length,但运气不佳。还有其他建议吗?

谢谢

我的代码:

    def removeAllAttributes(dom):
        for node in dom.childNodes:
            if node.attributes:
                for key in node.attributes.keys():
                    node.removeAttribute(key)
            if node.childNodes.length > 1:
                node = removeAllAttributes(dom)
        return dom

错误代码: RuntimeError: 超出最大递归深度

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    您处于无限循环中。这是您的问题行:

                node = removeAllAttributes(dom)
    

    我想你是说

                node = removeAllAttributes(node)
    

    【讨论】:

    • 好电话!那解决了它!我会投票给你的答案,但我没有足够的代表:)
    【解决方案2】:

    您可以尝试hasChildNodes() - 尽管如果直接检查 childNodes 属性不起作用,您可能会遇到其他问题。

    据推测,您的处理正在被抛出,因为您的元素没有元素子元素,但确实有文本子元素或其他东西。你可以这样检查:

    def removeAllAttributes(element):
        for attribute_name in element.attributes.keys():
            element.removeAttribute(attribute_name)
        for child_node in element.childNodes:
            if child_node.nodeType == xml.dom.minidom.ELEMENT_NODE:
                removeAllAttributes(child_node)           
    

    【讨论】:

    • 刚试了下,同样的错误码:RuntimeError: maximum recursion depth exceeded
    • 是的,您需要检查子节点的类型。查看修改后的版本。
    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 2017-04-30
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    相关资源
    最近更新 更多