如何使用minidom在python中检查xml节点是否有子节点?
如何使用minidom在python中检查xml节点是否有子节点 我正在编写一个递归函数来删除xml文件中的所有属性,在再次调用同一个函数之前,我需要检查一个节点是否有子节点 我所尝试的: 我尝试使用node.childNodes.length,但运气不太好。还有其他建议吗 谢谢 我的代码:如何使用minidom在python中检查xml节点是否有子节点?,python,xml,minidom,Python,Xml,Minidom,如何使用minidom在python中检查xml节点是否有子节点 我正在编写一个递归函数来删除xml文件中的所有属性,在再次调用同一个函数之前,我需要检查一个节点是否有子节点 我所尝试的: 我尝试使用node.childNodes.length,但运气不太好。还有其他建议吗 谢谢 我的代码: def removeAllAttributes(dom): for node in dom.childNodes: if node.attributes:
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
错误代码:
运行时错误:超过最大递归深度,您可以尝试-尽管如果直接检查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)
你处在一个无限循环中。以下是您的问题:
node = removeAllAttributes(dom)
我想你是说
node = removeAllAttributes(node)
刚刚尝试了一下,我得到了相同的错误代码:RuntimeError:maximum recursion depth ExceedeDayeah,您需要检查子节点的类型。查看编辑后的版本。打得好!这就解决了!我会支持你的答案,但我没有足够的代表:)