Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent ElementTree from adding namespaces to every element

I'm using ElementTree in Python to parse an xml file and add or remove elements in it.

In my XML file the root and the elements just below the root have a namespace, but all the other elements do not.

I see that ElementTree, when printing the modified tree, adds namespaces to every element.

Is there a proper way of telling ElementTree to just keep namespaces in the elements where they originally appeared?

like image 472
Ricky Robinson Avatar asked Oct 26 '25 10:10

Ricky Robinson


1 Answers

Try with this:

import xml.etree.ElementTree as ET
namespaces = {
    '':         'http://tempuri.org/',
    'soap':     'http://schemas.xmlsoap.org/soap/envelope/',
    'xsi':      'http://www.w3.org/2001/XMLSchema-instance',
    'xsd':      'http://www.w3.org/2001/XMLSchema',
}
for prefix, uri in namespaces.items():
    ET.register_namespace(prefix, uri)
like image 127
ssoto Avatar answered Oct 28 '25 23:10

ssoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!