简体   繁体   English

如何使用属性从 XSD 中创建 Python 对象

[英]How to create a Python object out of XSD with attributes

I am working on a project that is meant to take many different data sources and place them in a data table.我正在从事一个项目,该项目旨在获取许多不同的数据源并将它们放在数据表中。 To do this, we have a way to import the data through an XML document that has all of the fields defined in the table.为此,我们有一种方法可以通过 XML 文档导入数据,该文档具有表中定义的所有字段。 A few of these fields are required.其中一些字段是必需的。 Fields that are required have a minimum occurrences value of a non-zero positive integer.必需的字段具有非零正整数的最小出现值。

I have the XSD files for these XML documents.我有这些 XML 文档的 XSD 文件。 This isn't a 1 to 1 copy (since it's proprietary), but here is an example:这不是 1 对 1 的副本(因为它是专有的),但这是一个示例:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"   attributeFormDefault="unqualified">
    <xs:element name="Widget">
        <xs:complexType>
            <xs:all>
                <xs:element name="GuyWhoMadeWidget" nillable="true" minOccurs="1">
            </xs:all>
            <xs:attribute name="version" type="xs:string"/>
        <xs:complexType>
    </xs:element>
 </xs:schema>

What I want to be able to do is go into the <xs: element> element and do logic in Python on whether or not minOccurs is a non-zero value.我想要做的是进入<xs: element>元素并在 Python 中执行关于 minOccurs 是否为非零值的逻辑。 Here's some pseudocode:这是一些伪代码:

file_object = open(xsd_file)
required_fields = []
xsd_python_object = parse_xsd_to_python(file_object)
for element in xsd_python_object:
    if element.minOccurs != 0:
         required_fields.append(element.name)
print(required_fields)

Sample output here would be:此处的示例输出将是:

Required fields for "Widget" table:
GuyWhoMadeWidget

I have been looking into the xmlschema and lxml packages but their facilities leave me wanting, confused, or both.我一直在研究 xmlschema 和 lxml 包,但它们的功能让我想要、困惑或两者兼而有之。

I had a project where I needed to iterate a XSD file and I used the xmlschema library using something similar to this code:我有一个需要迭代 XSD 文件的项目,我使用了类似于以下代码的 xmlschema 库:

import xmlschema
schema = xmlschema.XMLSchema('your xsd file')

for xsd_component in schema.iter_components():
    if 'Element' in xsd_component:
        element_name = xsd_component.name

For example, printing the xsd_component would result in "XsdElement(name='sensor1value', occurs=[1, 1])" where I would use .split() function to retrieve the information that I needed.例如,打印 xsd_component 将导致“XsdElement(name='sensor1value',出现=[1, 1])”,我将使用 .split() 函数来检索我需要的信息。 The if is a example of what you could do. if 是你可以做什么的一个例子。 The documentation doesn't show everything you can use so check the other functions if you need something specific.该文档没有显示您可以使用的所有内容,因此如果您需要特定的东西,请检查其他功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM