Skip to content Skip to sidebar Skip to footer

Python Module Xml.etree.elementtree Modifies Xml Namespace Keys Automatically

I've noticed that python ElementTree module, changes the xml data in the following simple example : import xml.etree.ElementTree as ET tree = ET.parse('./input.xml') tree.write('.

Solution 1:

You would need to register the namespaces for your xml as well as their prefixes with ElementTree before reading/writing the xml using ElementTree.register_namespace function. Example -

import xml.etree.ElementTree as ET

ET.register_namespace('','http://schemas.xxx/2004/07/Server.Facades.ImportExport')
ET.register_namespace('i','http://www.a.org')
ET.register_namespace('d3p1','http://schemas.datacontract.org/2004/07/Management.Interfaces')

tree = ET.parse("./input.xml")
tree.write("./output.xml")

Without this ElementTree creates its own prefixes for the corresponding namespaces, which is what happens for your case.

This is given in the documentation -

xml.etree.ElementTree.register_namespace(prefix, uri)

Registers a namespace prefix. The registry is global, and any existing mapping for either the given prefix or the namespace URI will be removed. prefix is a namespace prefix. uri is a namespace uri. Tags and attributes in this namespace will be serialized with the given prefix, if at all possible.

(Emphasis mine)

Post a Comment for "Python Module Xml.etree.elementtree Modifies Xml Namespace Keys Automatically"