XML schema - child elements depending on the existence of an optional attribute

Is it possible to define the following scenario in XSD:

  • The parent has an attribute that

    is optional.

  • If the attribute is not

    present in XML, at least one child
    
    element must exists.
    
  • If a

    attribute is present, there can be
    
    zero or more child elements.
    

Example:

VALID

<parent externel-source="some_name" />



<parent externel-source="some_name">

  <child>some value</child>

</parent>



<parent>

  <child> some value</child>

</parent>

NOT VALID

<parent />
+5
source share
4 answers

No, I don’t think so.

-1
source

. : / - /.. (XSD - ), .
XSD .:-(
( ), stackOverFlow.

+3

, , , "". W3C XML Schema , . / , , . , SGML.

, , . Schematron; , .

0

, , xsi: type (, , , !). , xsd ;

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xs:element name="data">
    <xs:complexType>
        <xs:choice>
            <xs:element ref="elemParent" minOccurs="1"  maxOccurs="unbounded"/> 
        </xs:choice>
    </xs:complexType>
</xs:element>
<xs:element name="elemParent" type="ctBase"></xs:element>
<xs:complexType name="ctNoAttChildReq">
    <xs:complexContent>
        <xs:extension base="ctBase">
            <xs:sequence>
                <xs:element name="elemKid" type="xs:string"></xs:element>
                <xs:element name="elemKidAdditional" type="xs:string" minOccurs="0"></xs:element>
            </xs:sequence>              
        </xs:extension>
    </xs:complexContent>    
</xs:complexType>
<xs:complexType name="ctAttNoChild">
    <xs:complexContent>
        <xs:extension base="ctBase">
            <xs:attribute name="attReq" use="required"/>
        </xs:extension>
    </xs:complexContent>        
</xs:complexType>       
<xs:complexType name="ctBase" abstract="true">
    <xs:sequence/>
</xs:complexType>       

you get an instance that has either an attribute or one or more children, but you must have xsi: enter an instance that may or may not be show-stopper.

<data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:///C:/Xsds/StackOverflow_2070316_WIP.xsd">
<elemParent  attReq="Yo!" xsi:type="ctAttNoChild"/>
<elemParent xsi:type="ctNoAttChildReq">
    <elemKid>Adam</elemKid>
</elemParent>
<elemParent xsi:type="ctNoAttChildReq">
    <elemKid>Eve</elemKid>
    <elemKidAdditional>Sid</elemKidAdditional>
</elemParent>   

0
source

All Articles