【问题标题】:How to write to XML file while keeping the existing namespaces如何在保留现有命名空间的同时写入 XML 文件
【发布时间】:2019-10-26 11:31:11
【问题描述】:

当我解析 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 文件中。

【问题讨论】:

    标签: xml python-3.x parsing namespaces


    【解决方案1】:

    找到这个站点,其中包含我需要生成所需输出的示例: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')
    

    【讨论】:

      猜你喜欢
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多