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
-
4Why are both of the answers bringing up JSON, when your question never mentioned it? I feel like I'm missing something.Raleigh L.– Raleigh L.2023-05-07 02:29:37 +00:00Commented May 7, 2023 at 2:29
-
2Stumbled 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.Karri– Karri2024-05-29 06:11:38 +00:00Commented May 29, 2024 at 6:11
Add a comment
|
2 Answers
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.
Comments
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
kidman01
How do you know what the JSON data has to look like? That's where I'm currently tripping.
Ender
The xmlschema documentation on decoding the schema to JSON should give you an idea of how the JSON would look like.