Ricky Robinson
Ricky Robinson

Reputation: 22933

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?

Upvotes: 4

Views: 1648

Answers (1)

ssoto
ssoto

Reputation: 468

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)

Upvotes: 3

Related Questions