10

I have an existing xsd schema, and need to create (hopefully with Python) an XML file with some specific inputs. What is the best way to do it? I tried Element Tree and xmlschema, but I cannot tell if these allow to generate XML files starting from a known XSD schema. Thanks

2
  • 4
    Why are both of the answers bringing up JSON, when your question never mentioned it? I feel like I'm missing something. Commented May 7, 2023 at 2:29
  • 2
    Stumbled upon this post also while looking around for information on XML / XSD processing in Python. Don't understand why the answers are referring to JSON when the question doesn't mention anything about it. Commented May 29, 2024 at 6:11

2 Answers 2

2

here is a minimal working example with json data

import xmlschema
import json
from xml.etree.ElementTree import ElementTree

my_xsd = '<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="note" type="xs:string"/> </xs:schema>'

schema = xmlschema.XMLSchema(my_xsd)
data = json.dumps({'note': 'this is a Note text'})

xml = xmlschema.from_json(data, schema=schema, preserve_root=True)

ElementTree(xml).write('my_xml.xml')

for more complex xsd's I prefer working with generateDS, which creates very very solid classes from even for very large xsd files.

Sign up to request clarification or add additional context in comments.

Comments

1

In the end I did the following and seems to do the job:

import xmlschema
from xml.etree.ElementTree import ElementTree
# create XML from json, starting from known schema file 
sch      = 'schema_file.xsd'
schema   = xmlschema.XMLSchema(sch) 
jsondata = json of the data to be converted to XML
xml      = xmlschema.from_json(jsondata,schema=schema)
# write to XML
ElementTree(xml).write('myxml.xml')

2 Comments

How do you know what the JSON data has to look like? That's where I'm currently tripping.
The xmlschema documentation on decoding the schema to JSON should give you an idea of how the JSON would look like.

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.