在Python中根据XSD验证并填充XML的默认值
我想知道在用XSD验证我的XML时,如何填充默认值?如果我的属性没有被定义为 use="require"
,而是有 default="1"
,那么就可以从XSD把这些默认值填充到XML里。
举个例子:
原始的XML:
<a>
<b/>
<b c="2"/>
</a>
XSD模式:
<xs:element name="a">
<xs:complexType>
<xs:sequence>
<xs:element name="b" maxOccurs="unbounded">
<xs:attribute name="c" default="1"/>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
我想用XSD来验证原始的XML,并填充所有的默认值:
<a>
<b c="1"/>
<b c="2"/>
</a>
我该怎么在Python中实现这个?验证没有问题(比如用XMLSchema),但默认值的处理就有点麻烦了。
1 个回答
4
为了跟进我的评论,这里有一些代码
from lxml import etree
from lxml.html import parse
schema_root = etree.XML('''\
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a">
<xs:complexType>
<xs:sequence>
<xs:element name="b" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="c" default="1" type="xs:string"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>''')
xmls = '''<a>
<b/>
<b c="2"/>
</a>'''
schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema, attribute_defaults = True)
root = etree.fromstring(xmls, parser)
result = etree.tostring(root, pretty_print=True, method="xml")
print result
这段代码会给你
<a>
<b c="1"/>
<b c="2"/>
</a>
我稍微修改了一下你的XSD,把xs:attribute
放在xs:complexType
里面,并添加了模式命名空间。为了让你的默认值生效,你需要在etree.XMLParser()
中传入attribute_defaults=True
,这样就可以正常工作了。