When I parse an XML file, the existing namespaces within the file are removed when writing to a new XML file. How do I write to the new XML file while keeping the existing namespaces from the file I'm parsing?
I tried registering the namespaces based on the answer provided in this post, but do not see a difference in my end result: Saving XML files using ElementTree
from xml.etree import ElementTree as ET
ET.register_namespace('xsi', "http://www.w3.org/2001/XMLSchema-instance")
ET.register_namespace('xsd', "http://www.w3.org/2001/XMLSchema")
tree = ET.parse(file_path)
tree.write('./new.xml',
xml_declaration = True,
encoding = 'utf-8',
method = 'xml')
Original XML:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<settingsList>
<setting name="ConnectionProperties" serializeAs="Xml">
<value>
<SftpConnectionProperties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name></Name>
</SftpConnectionProperties>
</value>
</setting>
<setting name="WebUrl" serializeAs="String">
<value>https://test.com</value>
</setting>
</settingsList>
</userSettings>
</configuration>
XML after executing code:
<?xml version='1.0' encoding='utf-8'?>
<configuration>
<userSettings>
<settingsList>
<setting name="ConnectionProperties" serializeAs="Xml">
<value>
<SftpConnectionProperties>
<Name />
</SftpConnectionProperties>
</value>
</setting>
<setting name="WebUrl" serializeAs="String">
<value>https://test.com</value>
</setting>
</settingsList>
</userSettings>
</configuration>
I'd like to keep the namespaces from the original XML file in the new XML file.