[英]How to validate XML elements with XSD schema?
我想在XSD模式中為XML文檔使用條件。
我使用了限制,但功能並不強大。
這是我到目前為止所做的一個示例:
<xs:element name="Matricule">
<xs:complexType>
<xs:sequence>
<xs:element name="valeur">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"></xs:minInclusive>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element type="xs:string" name="backgroundcolor"/>
</xs:sequence>
</xs:complexType>
</xs:element>
此示例工作正常,但我只是檢查該值是否大於0。但是我想驗證該值是否為Integer以及該值為空。
也許是這樣的:
如果(值> 0 AND值<100 AND值='')
我在Google上發現了一個需要斷言的主題,因此我閱讀了文檔,然后做到了
<xs:element name="Matricule">
<xs:complexType>
<xs:sequence>
<xs:element name="valeur">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"></xs:minInclusive>
**<xs:assertion test="($value mod 10) = 0"/>**
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element type="xs:string" name="backgroundcolor"/>
</xs:sequence>
</xs:complexType>
</xs:element>
但這不起作用,我總是有一個錯誤。
例1的值:
<racine>
<row>
<Matricule>
<valeur>55</valeur>
<backgroundcolor></backgroundcolor>
</Matricule>
</row>
</racine>
示例2無值:
<racine>
<row>
<Matricule>
<valeur></valeur>
<backgroundcolor></backgroundcolor>
</Matricule>
</row>
</racine>
這兩個例子必須正確,但是這個沒有:
<racine>
<row>
<Matricule>
<valeur>gfd</valeur>
<backgroundcolor></backgroundcolor>
</Matricule>
</row>
</racine>
我懷疑您的意思是該值必須為0到100之間的數字,或者為空字符串。 如果真是這樣,您將在AND和OR之間陷入混亂。
空字符串不是xs:integer的有效實例,因此您不能將此類型定義為xs:integer的限制(因為限制只能定義為基值空間的子集的值空間)。
有兩種常見的方法來定義一個簡單類型,其中值必須為X或為空:
定義一個成員類型為X的聯合類型,以及一個從xs:string派生的類型,其唯一允許的值為“”
定義一個列表類型,其項類型為X,maxOccurs為1。
(在這種情況下,X是xs:integer
的限制,其中minInclusive = 0,maxInclusive = 100)。
我個人更喜歡(2):如果您使用的是模式感知型查詢和轉換,它會更好。 但是,如果您僅使用模式進行驗證,則沒有任何區別。
如果您需要接受空元素,則它們的內容不是整數類型,因為空字符串不代表數字。
您將不得不選擇xs:string類型,並僅使用接受整數或空字符串的模式對其進行限制。
這將工作:
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[0-9]*"/>
</xs:restriction>
</xs:simpleType>
如您所接受,它是0到9之間的數字,連續零次或更多次。
如果您的要求也低於100,我將讓您找到一種強制執行此附加條件的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.