如何定义xsd:complexType
以便它将验证以下两种结构?
<Element Key="test" Value="test" />
和
<Element Key="test">
<Value>test</Value>
</Element>
(并且不会验证这一个:)
<Element Key="test" Value="test">
<Value>another test</Value>
</Element>
答案 0 :(得分:3)
除非你使用Schematron之类的东西(在XSD 1.0之上),否则这在XSD 1.0中是不可能的。
这些是使用XSD 1.1的选项:断言和类型替代。您在下面看到的内容是根据Xerces对XSD 1.1规范的实现进行测试的。
(编辑包括Michael Kay的变体。在现实生活中,只选择一个。)
<?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" xmlns:xerces="http://xerces.apache.org">
<xsd:element name="Element">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Value" type="xsd:string" minOccurs="0"/>
</xsd:sequence>
<xsd:attribute name="Key" type="xsd:string" use="required"/>
<xsd:attribute name="Value" type="xsd:string"/>
<xsd:assert test="(Value and not(@Value)) or (@Value and not(Value))" xerces:message="Choose your Value wisely, one only."/>
<xsd:assert test="exists(Value) != exists(@Value)" xerces:message="One way..."/>
<xsd:assert test="count((Value,@Value))=1" xerces:message="Another way..."/>
</xsd:complexType>
</xsd:element>
<xsd:element name="Element1">
<xsd:alternative test="@Value" type="att"/>
<xsd:alternative test="not(@Value)" type="elt"/>
</xsd:element>
<xsd:complexType name="elt">
<xsd:sequence>
<xsd:element name="Value" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="Key" type="xsd:string" use="required"/>
</xsd:complexType>
<xsd:complexType name="att">
<xsd:attribute name="Key" type="xsd:string" use="required"/>
<xsd:attribute name="Value" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:schema>