How to check if an xml node has children in python with minidom?

╄→гoц情女王★ 提交于 2019-12-13 05:19:47

问题


How to check if an xml node has children in python with minidom?

I'm writing an recursive function to remove all attributes in an xml file and I need to check if an node has child nodes before calling the same function again.

What I've tried: I tried to use node.childNodes.length, but didn't have much luck. Any other suggestions?

Thanks

My Code:

    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

Error code: RuntimeError: maximum recursion depth exceeded


回答1:


You are in an infinite loop. Here is your problem line:

            node = removeAllAttributes(dom)

I think you mean

            node = removeAllAttributes(node)



回答2:


You could try hasChildNodes() - although if inspecting the childNodes attribute directly isn't working you may have other problems.

On a guess, your processing is being thrown off because your element has no element children, but does have text children or something. You can check for that this way:

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)           


来源:https://stackoverflow.com/questions/17622373/how-to-check-if-an-xml-node-has-children-in-python-with-minidom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!