簡體   English   中英

如何使用 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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM