XSD 定义 - 属性或元素



如何定义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>

最新更新