2010-10-10 97 views
1

我是XML新手,目前我正在使用XSD。我應該驗證基於信用卡的xml文檔。我已經完成了大部分任務,但我堅持聲明一個必須是正浮點數的元素,同時也允許該元素具有必需的屬性,該屬性必須具有與其關聯的3字母貨幣類型。XSD限制xsd類型,同時允許屬性

下面是XML元素的一個例子我要驗證:

<total curId="USD">4003.46</total> 

這是我有:

<xsd:element name="total" type="validAmount"/> 

    <xsd:complexType name="validAmount"> 
     <xsd:simpleContent> 
      <xsd:extension base="xsd:decimal"> 
       <xsd:attribute name= "curId" type = "currencyAttribute" use="required"/> 
      </xsd:extension> 
     </xsd:simpleContent> 
    </xsd:complexType> 

對於curId屬性:

<xsd:simpleType name="currencyAttribute"> 
    <xsd:restriction base="xsd:string"> 
     <xsd:pattern value="[A-Z]{3}"/> 
    </xsd:restriction> 
</xsd:simpleType> 

的我遇到的問題是試圖將擴展名更改爲限制,允許小數爲正數(也許是將其類型更改爲字符串並使用模式面將其限制爲正數)。但是,如果我這樣做,我用來驗證xml文檔的腳本會拋出錯誤。我知道我可能錯過了一些顯而易見的東西,但正如我所說的,我對此很陌生,因此任何幫助都將不勝感激。

回答

0

XSD不允許你在一個「鏡頭」中達到你想要的效果;您需要首先定義受限制的簡單類型(在restrictedDecimal類型中),然後使用屬性擴展該屬性(這裏的關鍵是使用simpleContent)。

<?xml version="1.0" encoding="utf-8" ?> 
<!-- XML Schema generated by QTAssistant/XSD Module (http://www.paschidev.com) --> 
<xsd:schema elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="total" type="validAmount"/> 

    <xsd:simpleType name="restrictedDecimal"> 
     <xsd:restriction base="xsd:decimal"> 
      <xsd:minInclusive value="0"/> 
     </xsd:restriction> 
    </xsd:simpleType> 

    <xsd:complexType name="validAmount"> 
     <xsd:simpleContent> 
      <xsd:extension base="restrictedDecimal"> 
       <xsd:attribute name= "curId" type = "currencyAttribute" use="required"/> 
      </xsd:extension> 
     </xsd:simpleContent> 
    </xsd:complexType> 

    <xsd:simpleType name="currencyAttribute"> 
     <xsd:restriction base="xsd:string"> 
      <xsd:pattern value="[A-Z]{3}"/> 
     </xsd:restriction> 
    </xsd:simpleType> 
</xsd:schema>