如何在保留现有名称空间的同时写入XML文件

时间:2019-06-12 02:37:52

标签: xml python-3.x parsing namespaces

当我解析XML文件时,写入新XML文件时,文件中现有的名称空间将被删除。在保留要解析的文件中现有名称空间的同时,如何写新XML文件?

我尝试根据本文中提供的答案注册名称空间,但最终结果没有发现差异: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')

原始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:

<?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>

我想将原始XML文件中的命名空间保留在新XML文件中。

1 个答案:

答案 0 :(得分:0)

找到了该网站,其中包含我需要产生所需输出的示例: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')