Conditional required elements in an XSD

后端 未结 1 1003
予麋鹿
予麋鹿 2020-12-14 23:11

I have a requirement for an xml schema which accepts either a request with the customer or with the customer id. If the customer Id is 0 then we need the customer data, if

相关标签:
1条回答
  • 2020-12-14 23:39

    This is possible in XSD 1.1; below is a simplified example, which assumes MainApplicant and WhereSigned are mandatory when CustomerId is equal to zero.

    <?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:xtm="http://paschidev.com/schemas/metadata/xtm">
        <xsd:complexType name="Request">
            <xsd:all>
                <xsd:element name="UserID" type="xsd:string" />
                <xsd:element name="Password" type="xsd:string" />
                <xsd:element name="ReferenceNumber" type="xsd:string" minOccurs="0"/>
                <xsd:element name="CustomerId" type="xsd:integer"/>
                <xsd:element ref="WhereSigned" minOccurs="0"/>
                <xsd:element name="ContactName" type="xsd:string" minOccurs="0" />
                <xsd:element name="ContactTelephone" type="xsd:string" minOccurs="0" />
                <xsd:element name="ContactFax" type="xsd:string" minOccurs="0" />
                <xsd:element name="ContactEmail" type="xsd:string" minOccurs="0" />
                <xsd:element ref="MainApplicant" minOccurs="0" />
                <xsd:element ref="JointApplicant" minOccurs="0" />
                <xsd:element ref="Asset" minOccurs="0" />
            </xsd:all>
            <xsd:assert test="CustomerId[. eq 0] and WhereSigned and MainApplicant or CustomerId[. ne 0]" />
        </xsd:complexType>
        <xsd:element name="Asset"/>
        <xsd:element name="MainApplicant" />
        <xsd:element name="JointApplicant" />
        <xsd:element name="WhereSigned" />  
    </xsd:schema>
    

    Minimum valid XML, when CustomerId is zero:

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Request">
        <UserID>UserID1</UserID>
        <Password>asodasqZX==</Password>
        <CustomerId>0</CustomerId>
        <WhereSigned/>
        <MainApplicant/>
    </root>
    

    When CustomerId is non-zero, then this is the minimum XML:

    <root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Request">
        <UserID>UserID1</UserID>
        <Password>asodasqZX==</Password>
        <CustomerId>1</CustomerId>
    </root>
    

    The conditional can be easily controlled (see the @test expression); add regular XSD constraints as needed (e.g. if your CustomerId needs to be greater than or equal to zero, then make it nonNegativeInteger, etc.)

    0 讨论(0)
提交回复
热议问题