Aditya Kuls Aditya Kuls - 2 years ago 83
Python Question

Deleting xml tags with particular Element name using xml.dom in python

How can we delete tags with particular Element name in an xml code using

) in python.

e.g. if we have the following xml code:

<?xml version="1.0"?>
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<description>An in-depth look at creating applications
with XML.</description>
<book id="bk102">
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
<book id="bk103">
<author>Corets, Eva</author>
<title>Maeve Ascendant</title>
<description>After the collapse of a nanotechnology
society in England, the young survivors lay the
foundation for a new society.</description>
<book id="bk104">
<author>Corets, Eva</author>
<title>Oberon's Legacy</title>
<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

How can we delete all the tags named
in python?

Answer Source

Select all the elements by title tag and remove them using removeChild


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

nodes = xmldoc.getElementsByTagName("title")

for node in nodes:
    parent = node.parentNode

print xmldoc.toxml()

You can also write new changes to xml file by :

with open("result.xml","w") as fs:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download