Skip to content Skip to sidebar Skip to footer

Parse An Xsd File Using Python

I am trying to generate an XML file from a given XML schema. I have been able to do it with pyxb library in python. But the problem is as the XSD gets huge it is impossible to manu

Solution 1:

This library seems to do what you want: https://pypi.org/project/xmlschema/

After skimming the documentation I have found this code example: https://xmlschema.readthedocs.io/en/latest/usage.html#xsd-declarations

>>> import xmlschema
>>> from pprint import pprint
>>> schema = xmlschema.XMLSchema('xmlschema/tests/test_cases/examples/vehicles/vehicles.xsd')
>>> schema.types
NamespaceView({'vehicleType': XsdComplexType(name='vehicleType')})
>>> pprint(dict(schema.elements))
{'bikes': XsdElement(name='vh:bikes', occurs=[1, 1]),
 'cars': XsdElement(name='vh:cars', occurs=[1, 1]),
 'vehicles': XsdElement(name='vh:vehicles', occurs=[1, 1])}
>>> schema.attributes
NamespaceView({'step': XsdAttribute(name='vh:step')})

So it looks like it can be used to create a python data-structure you can iterate through from an XSD file.

Also this question might be relevant: How to convert XSD to Python Class

Solution 2:

xsdata generates dataclasses from an XML schema. It can also render a dataclass as XML. A dataclass can be instantiated either by providing all the named parameters to the constructor (which can be statically checked using mypy or pylance) or using a dictionary and dacite.

As explained in the FAQ it is better to use Python 3.10 so that required fields become required arguments of the constructor. In order to do that execute xsdata init-config and set kwOnly=true in .xsdata.xml.

Solution 3:

You can generate XML file from XSD file:

import requests

withopen('file.xsd', 'r') as f:
    data = f.read()
r = requests.post('https://www.liquid-technologies.com/api/Converter', json={"Filename": "schema.xsd", "Type": "xsd", "Data": data, "TargetType": "xml", "Arguments": {"elementName": "Root", "elementNamespace": "", "addAnyAttributes": False, "addAnyElements": False, "forceOptionItemsToDepthOf": "4", "forceXsiNamespaceDelaration": False, "maxDepthToCreateOptionalItems": "7", "indent": "2", "indentChar": " ", "indentAttributes": False, "seed": "9722"}})
withopen('file.xml', 'w') as f:
    f.write(r.json()['Files'][0]['Data'])

Post a Comment for "Parse An Xsd File Using Python"