【问题标题】:create specific XML file from XSD file with python使用 python 从 XSD 文件创建特定的 XML 文件
【发布时间】:2020-05-09 19:14:08
【问题描述】:

我有一个现有的 xsd 架构,并且需要创建(希望使用 Python)一个带有一些特定输入的 XML 文件。 最好的方法是什么?我尝试了 Element Tree 和 xmlschema,但我不知道它们是否允许从已知的 XSD 模式开始生成 XML 文件。 谢谢

【问题讨论】:

    标签: python-3.x xml xsd


    【解决方案1】:

    最后我做了以下工作,似乎完成了这项工作:

    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】:

    这是一个带有 json 数据的最小工作示例

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

    对于更复杂的 xsd,我更喜欢使用 generateDS,它甚至可以为非常大的 xsd 文件创建非常可靠的类。

    【讨论】:

      猜你喜欢
      • 2012-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多