2016-06-09 48 views
0

如何在Python中使用xml.dom(而不是lxml.etree)在xml代碼中刪除具有特定元素名稱的標籤。使用python中的xml.dom刪除特定元素名稱的xml標籤

例如如果我們有如下的XML代碼:

<?xml version="1.0"?> 
<catalog> 
    <book id="bk101"> 
    <author>Gambardella, Matthew</author> 
    <title>XML Developer's Guide</title> 
    <genre>Computer</genre> 
    <price>44.95</price> 
    <publish_date>2000-10-01</publish_date> 
    <description>An in-depth look at creating applications 
    with XML.</description> 
    </book> 
    <book id="bk102"> 
    <author>Ralls, Kim</author> 
    <title>Midnight Rain</title> 
    <genre>Fantasy</genre> 
    <price>5.95</price> 
    <publish_date>2000-12-16</publish_date> 
    <description>A former architect battles corporate zombies, 
    an evil sorceress, and her own childhood to become queen 
    of the world.</description> 
    </book> 
    <book id="bk103"> 
    <author>Corets, Eva</author> 
    <title>Maeve Ascendant</title> 
    <genre>Fantasy</genre> 
    <price>5.95</price> 
    <publish_date>2000-11-17</publish_date> 
    <description>After the collapse of a nanotechnology 
    society in England, the young survivors lay the 
    foundation for a new society.</description> 
    </book> 
    <book id="bk104"> 
    <author>Corets, Eva</author> 
    <title>Oberon's Legacy</title> 
    <genre>Fantasy</genre> 
    <price>5.95</price> 
    <publish_date>2001-03-10</publish_date> 
    <description>In post-apocalypse England, the mysterious 
    agent known only as Oberon helps to create a new life 
    for the inhabitants of London. Sequel to Maeve 
    Ascendant.</description> 
    </book> 
</catalog> 

我們怎樣才能刪除使用python中xml.dom名爲<title>所有的標籤?

回答

0

通過title標籤選擇所有元素,並使用刪除它們removeChild

更新:

from xml.dom import minidom 
xmldoc = minidom.parse("book_xml.xml") 

nodes = xmldoc.getElementsByTagName("title") 

for node in nodes: 
    parent = node.parentNode 
    parent.removeChild(node) 

print xmldoc.toxml() 

你也可以寫通過向XML文件中的新變化:

with open("result.xml","w") as fs: 
    fs.write(xmldoc.toxml()) 
    fs.close() 
+0

你能請解釋如何在這裏使用'removeChild'?您的代碼只會打印我想要刪除的標籤。謝謝。 –

+0

希望這工作? – bhansa

+0

非常感謝。它(更新)完美地工作(對於未來的讀者:'doc_root'在這裏不是必需的,因爲我們沒有在任何地方使用它)。非常感謝。 –