1

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?

1 Answer 1

1

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"/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.