Question

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

Was it helpful?

Solution

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

            node = removeAllAttributes(dom)

I think you mean

            node = removeAllAttributes(node)

OTHER TIPS

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)           
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top