我们必须依赖于几个XML配置文件的应用程序。 XML文件定义了连接设置,轮询频率,多个用户帐户(使用XSD嵌套类型/序列)等等。
我有这些XML文件的XSD架构。下面小编摘录:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="FooExch" type="CConfigFooType"/>
<xs:complexType name="CConfigFooType">
<xs:sequence>
<xs:element name="_appID" type="xs:string"/>
...
<xs:element name="_logins" type="FooLoginsType" maxOccurs="unbounded"/>
<xs:element name="_passwords" type="FooPasswordType" maxOccurs="unbounded"/>
...
</xs:sequence>
</xs:complexType>
<xs:complexType name="FooLoginsType">
<xs:sequence>
<xs:element name="_name" type="xs:string"/>
<xs:element name="_adapterID" type="xs:int"/>
<xs:element name="_FooLogins" type="FooAccountType" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="FooAccountType">
<xs:sequence>
<xs:element name="_FooAccount" type="xs:string"/>
<xs:element name="_mktFeed" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="FooPasswordType">
<xs:sequence>
<xs:element name="_name" type="xs:string"/>
<xs:element name="_password" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
目的
我们的目标是让用户更方便地调整或添加设置。
我想提供一个采用YAML文件的脚本,并基于XSD输出XML配置(缺省值的缺省回退,可能位于default.yaml
文件中)。
我们还需要能够将YAML“附加”到XML中,因为用户可以拥有一个只定义其用户帐户的YAML,并且我们会将其导入现有的用户帐户列表在现有的XML文件中。
3.方法
到目前为止,我使用GenerateDS(http://www.rexx.com/~dkuhlman/generateDS.html)生成从XSD一个Python包装。
使用它,我可以创建一个表示XML模式的Python对象,然后将它们导出到XML。
现在的问题是我如何从YAML到XML?
理想情况下,我想要一个通用循环,只是运行每个值,并将其添加到Python表示。
我最初的想法是使用getattr(config_wrapper, "yaml_name") = yaml_value
并遍历YAML中的每个值,然后捕获AttributeError
中的任何不在XSD中的内容。
我的第一个问题 - 这个方法有什么问题,或者是否有更多的Pythonic /清洁方法?有没有更聪明的方法来解决这个问题?
我的第二个问题是 - 对于上面的XSD部分,我们需要使用用户名/密码进行嵌套登录。我知道PyYAML提供了嵌套集合,但是我还不太确定这将如何与GenerateDS绑定,或者我如何使其通用性足以工作可靠。
干杯, 维克多