Remove namespace and prefix from xml in python using lxml

speedyrazor picture speedyrazor · Aug 10, 2013 · Viewed 44.9k times · Source

I have an xml file I need to open and make some changes to, one of those changes is to remove the namespace and prefix and then save to another file. Here is the xml:

<?xml version='1.0' encoding='UTF-8'?>
<package xmlns="http://apple.com/itunes/importer">
  <provider>some data</provider>
  <language>en-GB</language>
</package>

I can make the other changes I need, but can't find out how to remove the namespace and prefix. This is the reusklt xml I need:

<?xml version='1.0' encoding='UTF-8'?>
<package>
  <provider>some data</provider>
  <language>en-GB</language>
</package>

And here is my script which will open and parse the xml and save it:

metadata = '/Users/user1/Desktop/Python/metadata.xml'
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
open(metadata)
tree = etree.parse(metadata, parser)
root = tree.getroot()
tree.write('/Users/user1/Desktop/Python/done.xml', pretty_print = True, xml_declaration = True, encoding = 'UTF-8')

So how would I add code in my script which will remove the namespace and prefix?

Answer

SergiyKolesnikov picture SergiyKolesnikov · Aug 22, 2018

First, use lxml.etree.QName to remove namespace prefixes from the tag names:

>>> root.tag
'{http://apple.com/itunes/importer}package'
>>> etree.QName(root).localname
'package'

Then, use lxml.etree.cleanup_namespaces() to remove unused namespace declarations from the tree.

Complete example:

from lxml import etree

input_xml = '''
<package xmlns="http://apple.com/itunes/importer">
  <provider>some data</provider>
  <language>en-GB</language>
</package>
'''
root = etree.fromstring(input_xml)

# Remove namespace prefixes
for elem in root.getiterator():
    elem.tag = etree.QName(elem).localname
# Remove unused namespace declarations
etree.cleanup_namespaces(root)

print(etree.tostring(root).decode())

Output XML:

<package>
  <provider>some data</provider>
  <language>en-GB</language>
</package>