Вопрос

How to define xsd:complexType such that it will validate both of the following constructs?

<Element Key="test" Value="test" />

and

<Element Key="test">
    <Value>test</Value>
</Element>

(and won't validate this one:)

<Element Key="test" Value="test">
    <Value>another test</Value>
</Element>
Это было полезно?

Решение

This is not possible in XSD 1.0 unless you use something such as Schematron (on top of XSD 1.0).

These are your options using XSD 1.1: assertions and type alternatives. What you see below was tested based on Xerces's implementation of the XSD 1.1 spec.

(Edited to include Michael Kay's variations. In real life, choose only one.)

<?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>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top