2010-06-10 64 views
3

如何在使用XSD進行驗證期間填充XML中的默認值?如果我的屬性未被定義爲use="require"並且具有default="1",則可以將這些默認值從XSD填充到XML。在Python中基於XSD驗證和填充默認值

例子: 原始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)。問題是默認值。

+0

我剛剛問過類似的問題,看看這是否支持任何語言的任何驗證庫http://stackoverflow.com/questions/4900867/is-there-a-xml-schema-validation-library-那支持的默認屬性價值 – 2011-02-04 17:21:09

+0

但我從來沒有這樣做,但是,從[lxml文檔](http://lxml.de/validation.html#validation-at-parse-time)它看起來就像它會將默認值「編織」到文檔中一樣。 – 2011-11-14 22:20:53

回答

3

要跟進我的意見,這裏的一些代碼

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和添加的架構命名空間。要填寫默認值,您需要將attribute_defaults=True傳遞給etree.XMLParser(),它應該可以工作。

+0

爲什麼需要在xs:complexType中包裝xs:屬性? – PoltoS 2011-11-20 23:38:23

+0

也許你也知道如何回答這個問題:http://stackoverflow.com/questions/4799838/is-it-possible-to-get-the-type-of-an-xml-node-as-it-被定義的功能於XSD – PoltoS 2011-11-21 00:54:12