4

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?

8
  • Is this what you're after? Looks like it's a hack where you modify the whole tree with a regular expression before running the parser on it. Commented Aug 1, 2017 at 9:20
  • Hmm... looks like a violent hack. I don't want to remove namespaces all together, I would like to keep them where they appear in the original file. Commented Aug 1, 2017 at 9:27
  • Does that also happen with unmodified tree? "I see that ElementTree, when printing the modified tree, adds namespaces to every element." Commented Aug 1, 2017 at 13:56
  • Yes. I also noticed that some inner elements that were unaltered by my code had their original namespace removed and replaced by that of the parent subtree... Commented Aug 1, 2017 at 14:06
  • 2
    As I commented in stackoverflow.com/q/38663191/407651, if you can use lxml (lxml.de) instead of ElementTree, then that is a solution, I think. Commented Aug 2, 2017 at 9:24

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.