Assume that I've the following XML which I want to modify using Python's ElementTree
:
<root xmlns:prefix="URI">
<child company:name="***"/>
...
</root>
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:
<root xmlns:ns0="URI">
<child ns0:name="***"/>
...
</root>
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
andURI
- It can not be used with default namespace.
e.g. If the xml looks like:
<root xmlns="http://uri">
<child name="name">
...
</child>
</root>
It will be transfomed to something like:
<ns0:root xmlns:ns0="http://uri">
<ns0:child name="name">
...
</ns0:child>
</ns0:root>
As you can see, the default namespace is changed to ns0
.
Is there any way to solve this problem with ElementTree
?
ET.register_namespace(...
. Edit your Question to minimal reproducible example to show how you use it. – Coonxmlns:prefix="URI"
with any prefix and URI. – Underplotregister_namespace()
. If you don't like that, try lxml instead. – Abrasiveprefix
andURI
when usingregister_namespace()
. As I said,I don't want to hard code the namespace
. Is there any way to do this withElementTree
? – Underplotlxml
namespaceslxml.etree
allows you to look up the current namespaces defined for a node through the.nsmap
property:. – Coon