【问题标题】:how to format attributes, prefixes, and tags using xml.etree.ElementTree Python如何使用 xml.etree.ElementTree Python 格式化属性、前缀和标签
【发布时间】:2021-03-03 05:21:25
【问题描述】:

我正在尝试创建一个 python 脚本,该脚本将创建一个模式,然后根据现有引用填充数据。

这是我需要创建的:

<srp:root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

这就是我所拥有的:

from xml.etree.ElementTree import *
from xml.dom import minidom

def prettify(elem):
    rough_string = tostring(elem, "utf-8")
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="  ")

ns = { "SOAP-ENV": "http://www.w3.org/2003/05/soap-envelope", 
    "SOAP-ENC": "http://www.w3.org/2003/05/soap-encoding",
    "xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "srp": "http://www.-redacted-standards.org/Schemas/MSRP.xsd"}

def gen():
    root = Element(QName(ns["xsi"],'root'))
    print(prettify(root))
gen()

这给了我:

如何修复它以使前面匹配?

【问题讨论】:

    标签: python xml elementtree xml-namespaces


    【解决方案1】:

    您要求的确切结果不完整,但通过对 gen() 函数进行一些编辑,可以生成格式正确的输出。

    根元素应绑定到http://www.-redacted-standards.org/Schemas/MSRP.xsd 命名空间(srp 前缀)。为了生成xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 声明,必须在 XML 文档中使用命名空间。

    def gen():
        root = Element(QName(ns["srp"], 'root'))
        root.set(QName(ns["xsi"], "schemaLocation"), "whatever") # Add xsi:schemaLocation attribute
        
        register_namespace("srp", ns["srp"])                     # Needed to get 'srp' instead of 'ns0'
        
        print(prettify(root))
    

    结果(为便于阅读添加了换行符):

    <?xml version="1.0" ?>
    <srp:root xmlns:srp="http://www.-redacted-standards.org/Schemas/MSRP.xsd"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="whatever"/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2013-03-26
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      相关资源
      最近更新 更多