create specific XML file from XSD file with python

Viewed 6396

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 Answers

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

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.

Related