PyXB的端到端示例。从XSD模式到XML文档

2024-05-15 16:29:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难开始学习PyXB

假设我有an XSD file(一个XML模式)。我想:

  1. 使用PyXB根据模式定义Python对象。
  2. 将这些对象另存为满足架构的XML文件。

我怎么能用PyXB呢?下面是一个XSD文件(来自Wikipedia)的simple example,它编码一个地址,但是我甚至很难开始。

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Address">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FullName" type="xs:string" />
        <xs:element name="House" type="xs:string" />
        <xs:element name="Street" type="xs:string" />
        <xs:element name="Town" type="xs:string" />
        <xs:element name="County" type="xs:string" minOccurs="0" />
        <xs:element name="PostCode" type="xs:string" />
        <xs:element name="Country" minOccurs="0">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:enumeration value="IN" />
              <xs:enumeration value="DE" />
              <xs:enumeration value="ES" />
              <xs:enumeration value="UK" />
              <xs:enumeration value="US" />
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

更新

一旦我跑了

pyxbgen -u example.xsd -m example

我得到一个有以下类的example.py

example.Address             example.STD_ANON
example.CTD_ANON            example.StringIO
example.CreateFromDOM       example.pyxb
example.CreateFromDocument  example.sys
example.Namespace           

我想我理解CreateFromDocument的作用-它可能读取一个XML并创建相应的python对象-,但是我使用哪个类来创建一个新的对象,然后将其保存到XML中?


Tags: 文件对象namestringvalueaddressexampleschema
1条回答
网友
1楼 · 发布于 2024-05-15 16:29:59

一个简单的google搜索会带来这样的结果:http://pyxb.sourceforge.net/userref_pyxbgen.html#pyxbgen

特别是说:

Translate this into Python with the following command:

pyxbgen -u po1.xsd -m po1

The -u parameter identifies a schema document describing contents of a namespace. The parameter may be a path to a file on the local system, or a URL to a network-accessible location like http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd. The -m parameter specifies the name to be used by the Python module holding the bindings generated for the namespace in the preceding schema. After running this, the Python bindings will be in a file named po1.py.

更新后编辑

现在已经生成了Address类和所有相关的帮助程序,请查看http://pyxb.sourceforge.net/userref_usebind.html以了解如何使用它们。对于您的特定问题,您需要学习“在Python代码中创建实例”一段。基本上,要从应用程序数据生成XML,只需执行以下操作:

import example
address = Address()
address.FullName = "Jo La Banane"
# fill other members of address
# ...
with open('myoutput.xml', 'w') as file
    f.write(address.toxml("utf-8"))

现在由你来好奇和阅读正在生成的代码,pyxb的doc,调用各种生成的方法和实验!

相关问题 更多 >