如何使用 xml.etree.ElementTree Python 格式化属性、前缀和标签

how to format attributes, prefixes, and tags using xml.etree.ElementTree Python

我正在尝试创建一个 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()

这给了我:

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

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

您要求的确切结果不完整,但通过对 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"/>