2

I am trying to parse a XML file, modify some values, and write the file back using the python code below. When writing the file back, it changes the namespace declaration location from assemblyBinding element to root (configuration) element. Due to this I am having other issues when that XML file is consumed. Is it possible to maintain the location of namespace declaration?

import xml.etree.ElementTree as ET
ET.register_namespace('', "urn:schemas-microsoft-com:asm.v1")

tree = ET.parse('abc.xml')
root = tree.getroot()       
..
tree.write('abc.xml')

Original Configuration

<configuration>      
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">         
        <assemblyIdentity culture="neutral"/>                  
    </assemblyBinding>
  </runtime>
</configuration>

Modified Configuration

<configuration xmlns="urn:schemas-microsoft-com:asm.v1">      
  <runtime>
    <assemblyBinding>          
        <assemblyIdentity culture="neutral"/>               
    </assemblyBinding>
  </runtime>
</configuration>

I am using Python 3.7 Thank you.

Marshal
  • 6,551
  • 13
  • 55
  • 91
  • Does the consuming application care if a prefix is used? If you add a prefix to the `register_namespace` (like `ET.register_namespace('asm', "urn:schemas-microsoft-com:asm.v1")`), there's now a prefix but the actual namespaces are correct in the output. If the consuming application handles XML correctly, the prefix shouldn't matter; only the namespace uri is important. Great question btw. +1 – Daniel Haley Feb 15 '19 at 22:11
  • 2
    There is not much you can do about this (apart from switching to lxml). See https://stackoverflow.com/q/45990761/407651 – mzjn Feb 16 '19 at 06:21
  • @DanielHaley: Thanks Daniel. I tried that earlier, but doesn't help, and that's why I deduced that it's not the namespace resolution, but namespace location which is causing the issue. I believe I may have to go with mzjn's suggested approach. – Marshal Feb 18 '19 at 13:22
  • @mzjn: Using lxml resolved the issue. Thank you. – Marshal Feb 19 '19 at 15:55

0 Answers0