Определение 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>

1 ответ

Решение

Это невозможно в 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>
Другие вопросы по тегам