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?

Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185
  • Is [this](https://stackoverflow.com/a/15641319/4288043) 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. – cardamom Aug 01 '17 at 09: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. – Ricky Robinson Aug 01 '17 at 09:27
  • Does that also happen with _**unmodified**_ tree? "_I see that ElementTree, when printing the modified tree, adds namespaces to every element._" – stovfl Aug 01 '17 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... – Ricky Robinson Aug 01 '17 at 14:06
  • Similar to https://stackoverflow.com/q/38438921/407651 and https://stackoverflow.com/q/38663191/407651 – mzjn Aug 01 '17 at 19:23
  • Yes, similar to questions that never received an answer. So I suppose there's no solution... – Ricky Robinson Aug 02 '17 at 08:19
  • 1
    As I commented in https://stackoverflow.com/q/38663191/407651, if you can use lxml (http://lxml.de) instead of ElementTree, then that is a solution, I think. – mzjn Aug 02 '17 at 09:24
  • @RickyRobinson, I post a solution, with the namespace/xml structure unchanged, hope it helps. The link here: https://stackoverflow.com/questions/35574815/how-to-force-elementtree-to-keep-xmlns-attribute-within-its-original-element/66123074#66123074 – XYZ Feb 09 '21 at 16:40

1 Answers1

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)
ssoto
  • 469
  • 5
  • 19