Hi everyone,

Does anyone know how to remove a particular attribute in XML by using Python?

<country>
<city capital="Paris">Paris</city>
............
............
</country>
<country>
<city capital="Helsinki">Helsinki</city>
............
............
</country>
<country>
<city capital="Bogota">Bogota</city>
............
............
</country>

I just wanna delete or remove Paris and Helsinki here by using SAX or DOM. How could I do it?

Thanks for your help.

Have a nice day!!!

Using minidom:

from xml.dom import minidom

doc = '''<?xml version="1.0" ?>
<countries>
<country>
<city capital="Paris">Paris</city>
</country>
<country>
<city capital="Helsinki">Helsinki</city>
</country>
<country>
<city capital="Bogota">Bogota</city>
</country>
</countries>'''

docXML = minidom.parseString(doc)
for elem in docXML.getElementsByTagName("city"):
    elem.removeAttribute("capital")
print docXML.toprettyxml(indent="  ", newl="")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.