[英]Validating and filling default values in XML based on XSD in Python
在針對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)。 問題是默認值。
要跟進我的評論,這里有一些代碼
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:complexType
包裝了xs:attribute
並添加了schema命名空間。 要填寫默認值,您需要將attribute_defaults=True
傳遞給etree.XMLParser()
,它應該可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.