[英]Can't properly remove nested xml tags with Python using xml minidom
我正在嘗試使用 Python 3.8 並內置 xml.dom.minidom 刪除 xml 表示為字符串的一些嵌套標簽。 結果令人驚訝,解析器只刪除第一個或打開的標簽並留下封閉的標簽。 當然我錯過了一些東西,但我看不到它是什么。
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())
如果您只想刪除所有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())
Output:
<?xml version="1.0" ?>
<root>
<test1></test1>
<test1></test1>
<test1></test1>
<test1></test1>
</root>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.