【问题标题】:Can't properly remove nested xml tags with Python using xml minidom无法使用 xml minidom 使用 Python 正确删除嵌套的 xml 标签
【发布时间】:2020-07-16 00:26:06
【问题描述】:

我正在尝试删除一些嵌套的 xml 标记,这些标记使用 Python 3.8 表示为字符串并内置在 xml.dom.minidom 中。结果令人惊讶,解析器只删除第一个或打开的标签并留下封闭的标签。当然我错过了一些东西,但我看不到它是什么。

import xml.dom.minidom as xml

StringXML = "<root><test1><test2></test2></test1><test1><test2></test2></test1><test1><test2></test2></test1><test1><test2></test2></test1></root>"

a = xml.parseString(StringXML)
num = 0

while (a.getElementsByTagName('test2').length > num):
  if(a.getElementsByTagName('test2')[num]):

    a.getElementsByTagName('test2')[num].parentNode.removeChild(a.getElementsByTagName('test2')[num])
    a.getElementsByTagName('test2')[num].unlink()
  num = num +1

print(a.toxml())

【问题讨论】:

    标签: python python-3.x xml tags minidom


    【解决方案1】:

    如果您只想删除所有test2 元素,则无需增加计数器。只需遍历 getElementsByTagName('test2') 返回的项目。

    import xml.dom.minidom as xml
    
    StringXML = "<root><test1><test2></test2></test1><test1><test2></test2></test1><test1><test2></test2></test1><test1><test2></test2></test1></root>"
    
    a = xml.parseString(StringXML)
    
    for test2 in a.getElementsByTagName('test2'):
        test2.parentNode.removeChild(test2)
    
    # Need to add empty text node to get <test1></test1> serialization
    for test1 in a.getElementsByTagName('test1'):
        test1.appendChild(a.createTextNode(''))
    
    print(a.toprettyxml())
    

    输出:

    <?xml version="1.0" ?>
    <root>
        <test1></test1>
        <test1></test1>
        <test1></test1>
        <test1></test1>
    </root>
    

    【讨论】:

    • 仍然没有我想要的,我想要打开和关闭标签的结果,例如
    • 请注意,从 XML 的角度来看,&lt;test1/&gt;&lt;test1&gt;&lt;/test1&gt; 完全相同。
    • 以后我会尝试使用etree。 Minidom有点混乱。如您所见,我不是python开发人员:-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-22
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多