使用 python 解析 XSD 文件

Parse an XSD file using python

我正在尝试从给定的 XML 模式生成 XML 文件。我已经能够使用 python 中的 pyxb 库来完成它。但问题是随着 XSD 变大,不可能手动对每个标签进行编码。是否有任何 python 库从给定的 XSD 文件创建数据结构,该文件可以通过

迭代

这个库似乎可以满足您的要求:https://pypi.org/project/xmlschema/

浏览文档后,我找到了这个代码示例: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')})

所以看起来它可以用来创建一个 python 数据结构,您可以从 XSD 文件中迭代。

这个问题也可能是相关的:How to convert XSD to Python Class

您可以从 XSD 文件生成 XML 文件:

import requests

with open('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"}})
with open('file.xml', 'w') as f:
    f.write(r.json()['Files'][0]['Data'])

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.

FAQ 中所述,最好使用 Python 3.10,以便必填字段成为构造函数的必填参数。为此,执行 xsdata init-config 并在 .xsdata.xml.

中设置 kwOnly=true