简体   繁体   English

删除 XML 文档中每个节点的所有属性

[英]Remove all the attributes of every node in an XML document

I have a Node(element) object of an XML Document.我有一个 XML 文档的 Node(element) 对象。 I need to remove all the attributes of it's and it's Sub Nodes.我需要删除它和它的子节点的所有属性。 How do i do this in python?我如何在 python 中做到这一点? i'm using xml.dom.minidom我正在使用xml.dom.minidom

Something along the lines of:类似的东西:

dom = xml.dom.minidom.parseString(document)

for node in dom.childNodes:
    if node.attributes:
        for key in node.attributes.keys():
            node.removeAttribute(key)

Rob's answer won't work nowadays, it will cause a RunTimeError when you try to remove a key from a dict you are using as an Iterator Rob 的答案现在不起作用,当您尝试从用作Iteratordict删除key时,它会导致RunTimeError

So, before trying to remove you should clone the keys first, something like this would work因此,在尝试删除之前,您应该先克隆密钥,这样的操作会起作用

keys = list(xml_node.attributes.keys()) if xml_node.attributes else []
for attribute in keys:
    xml_node.removeAttribute(attribute)

这很容易使用PyQuery ,它有一个删除属性方法: http : //packages.python.org/pyquery/api.html#pyquery.pyquery.PyQuery.removeAttr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM