0

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.

Mike
  • 21
  • 2

1 Answers1

0

Found this site which contained an example of what I needed to produce the desired output: http://effbot.org/zone/element-namespaces.htm

def parse_xmlns(file):

    events = "start", "start-ns"

    root = None
    ns_map = []

    for event, elem in ET.iterparse(file, events):

        if event == "start-ns":
            ns_map.append(elem)

        elif event == "start":
            if root is None:
                root = elem
            for prefix, uri in ns_map:
                elem.set("xmlns:" + prefix, uri)
            ns_map = []

    return ET.ElementTree(root)

tree = parse_xmlns(config_path)

tree.write('./new.xml',
           xml_declaration = True,
           encoding = 'utf-8',
           method = 'xml')
Mike
  • 21
  • 2