Assume that I've the following XML which I want to modify using Python's ElementTree:
...
I'm doing some modification on the XML file like this:
import xml.etree.ElementTree as ET
tree = ET.parse('filename.xml')
# XML modification here
# save the modifications
tree.write('filename.xml')
Then the XML file looks like:
...
As you can see, the namepsace prefix changed to ns0. I'm aware of using ET.register_namespace() as mentioned here.
The problem with ET.register_namespace() is that:
You need to know prefix and URI
It can not be used with default namespace.
e.g. If the xml looks like:
...
It will be transfomed to something like:
...
As you can see, the default namespace is changed to ns0.
Is there any way to solve this problem with ElementTree?
解决方案
Here is the way to preserve the namespaces' prefix and URI:
def register_all_namespaces(filename):
namespaces = dict([node for _, node in ET.iterparse(filename, events=['start-ns'])])
for ns in namespaces:
ET.register_namespace(ns, namespaces[ns])
This method should be called before calling the [ET].write() method.