如何定义xsd:complexType
这样它将验证以下两个构造?
<Element Key="test" Value="test" />
和
<Element Key="test">
<Value>test</Value>
</Element>
(并且不会验证这个:)
<Element Key="test" Value="test">
<Value>another test</Value>
</Element>
这在 XSD 1.0 中是不可能的,除非您使用诸如 Schematron(在 XSD 1.0 之上)之类的东西。
这些是您使用 XSD 1.1 的选项:断言和类型替代。您在下面看到的内容是根据 Xerces 对 XSD 1.1 规范的实现进行测试的。
(编辑包括迈克尔凯的变化。在现实生活中,只选择一个。)
<?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>