2011-03-10 22 views
1

我有以下要求,並試圖確定如何最好地模擬XSD來表示這些要求。如何在XSD中表示具有耦合屬性類型的元素的序列?

我有很多XML元素的實例,比如<box>。每個<box>都有一個必需的屬性t="[box-type]",每個盒子都有一個特定的類型,比如說t="tall"有另一個必需的屬性v="10",它表示高盒子的高度。所有<box> es屬性都具有tv屬性,但是對v屬性接受哪些值的限制取決於它們的t屬性的值。

例如,採取以下XML:現在

<box t="tall" v="10"/> 
<box t="named" v="George"/> 
<box t="colored" v="green"/> 

,在我的XSD我需要能夠代表這些元素的序列。我的想法是做類似的東西僅列出了所有允許箱類型在我的順序如下(在下面的代碼片段的末尾):

<xsd:simpleType name="box_types"> 
    <xsd:restriction base="xsd:token"> 
     <xsd:enumeration value="tall" /> 
     <xsd:enumeration value="named" /> 
     <xsd:enumeration value="colored" /> 
    </xsd:restriction> 
</xsd:simpleType> 

<!--Box base--> 
<xsd:complexType name="box_type"> 
    <xsd:attribute name="t" use="required" type="box_types"/> 
    <xsd:attribute name="v" use="required"/> 
</xsd:complexType> 

<!--Box concrete types--> 
<xsd:complexType name="tall_box_type"> 
    <xsd:complexContent> 
     <xsd:extension base="box_type"> 
      <xsd:attribute name="t" fixed="tall" use="required"/> 
      <xsd:attribute name="v" type="xsd:int" use="required"/> 
     </xsd:extension> 
    </xsd:complexContent> 
</xsd:complexType> 

<xsd:complexType name="named_box_type"> 
    <xsd:complexContent> 
     <xsd:extension base="box_type"> 
      <xsd:attribute name="t" fixed="named" use="required"/> 
      <xsd:attribute name="v" type="xsd:string" use="required"/> 
     </xsd:extension> 
    </xsd:complexContent> 
</xsd:complexType> 

<xsd:complexType name="colored_box_type"> 
    <xsd:complexContent> 
     <xsd:extension base="box_type"> 
      <xsd:attribute name="t" fixed="colored" use="required"/> 
      <xsd:attribute name="v" type="xsd:token" use="required"/> 
     </xsd:extension> 
    </xsd:complexContent> 
</xsd:complexType> 

<!--And finally, the place where boxes show up--> 
<xsd:complexType name="box_usage"> 
    <xsd:sequence> 
     <xsd:element name="box" type="tall_box_type"/> 
     <xsd:element name="box" type="named_box_type"/> 
     <xsd:element name="box" type="colored_box_type"/> 
    </xsd:sequence> 
</xsd:complexType> 

不幸的是,這不是一個有效的XSD - VS給出我的幾個錯誤,最不幸的是Elements with the same name and in the same scope must have the same type。有關如何在XSD中表示這些t/v耦合屬性限制的任何建議?

回答

1

XML Schema 1.0無法驗證值之間的依賴關係。您的選項是:

  1. 更改您的XML。例如,使用tallBox,colorBoxnameBox作爲元素名稱。
  2. 使用XSD驗證一般結構並使用程序邏輯(或Schematron或XSLT樣式表等其他工具)驗證值。
  3. 使用XML Schema 1.1,它可以驗證數值約束,但通常不受支持。
+0

好的,謝謝你的建議! – 2011-03-14 04:02:50

相關問題