rob ell
rob ell

Reputation: 45

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

I'm trying to create a python script that will create a schema to then fill data based on an existing reference.

This is what I need to create:

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

this is what I have:

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()

which gives me:

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

how do I fix it so that the front matches?

Upvotes: 1

Views: 581

Answers (1)

mzjn
mzjn

Reputation: 50947

The exact result that you ask for is incomplete, but with a few edits to the gen() function, it is possible to generate well-formed output.

The root element should be bound to the http://www.-redacted-standards.org/Schemas/MSRP.xsd namespace (srp prefix). In order to generate the xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" declaration, the namespace must be used in the XML document.

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

Result (linebreaks added for readability):

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

Upvotes: 1

Related Questions