2009-04-18 82 views
53

有沒有辦法指定XSD中需要2個屬性中的一個?XSD - 需要2個屬性之一?

例如,我有這樣的定義。

<xs:attribute name="Name" type="xs:string" use="optional" /> 
<xs:attribute name="Id" type="xs:string" use="optional" /> 

我希望能夠定義這些中的至少一個是必需的。那可能嗎?

回答

40

不,我不認爲你可以用屬性來做到這一點。您可以將兩個< xs:元素>併入< xs:choice > - 但對於屬性,恐怕沒有等價的構造。

馬克

9

馬克是完全正確的...你不能有XS:在XSD選擇父元素:一個XS內部屬性的子元素。

邏輯似乎是,如果一個元素的兩個實例具有互斥的一組屬性,那麼它們在邏輯上是兩個不同的元素。

對此的解決方法已由Jeni Tennison here提出。

20

XSD 1.1將爲您做到這一點使用斷言讓。

<xsd:element name="remove"> 
    <xsd:complexType>       
     <xsd:attribute name="ref" use="optional"/> 
     <xsd:attribute name="uri" use="optional"/> 
     <xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>    
    </xsd:complexType> 
</xsd:element> 
+1

不錯的解決方案,但自2012年發佈以來(http://www.w3.org/TR/xmlschema11-1/),我使用.NET 4.0(2010年發佈),它是不支持。 .NET 4.5支持它嗎?示例類:https://msdn.microsoft.com/en-us/library/swxzdhc0(v=vs.110).aspx – 2015-10-08 16:37:33

0

的例子定義了一個名爲「人」,它必須包含一個「僱員」元素或「構件」元素的元素。

<xs:element name="person"> 
    <xs:complexType> 
    <xs:choice> 
     <xs:element name="employee" type="employee"/> 
     <xs:element name="member" type="member"/> 
    </xs:choice> 
    </xs:complexType> 
</xs:element> 
+0

小心引用您的源代碼? http://www.w3schools.com/xml/el_choice.asp – Reisclef 2016-04-16 20:12:11