问题
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