How to specify in an XML schema that either one of two fields must be present?

后端 未结 2 672
猫巷女王i
猫巷女王i 2021-02-13 01:49

I want to specify that either fieldname or freetext must always be present in XML files that apply to this XSD. Is there a way to do that?



        
相关标签:
2条回答
  • 2021-02-13 02:09

    So, you want either fieldname or freetext and not both? or maybe both? and then dbtablename optionally?

    Here is 1 or 2 of the elements:

    <xs:choice minOccurs="1" maxOccurs="2">
        <xs:element name="fieldname" type="xs:string"/>
        <xs:element name="freetext" type="xs:string"/>
        <xs:element name="dbtablename" type="xs:string"/>
    </xs:choice>
    

    Is this what you want? or did you want dbtablename to be separate?

    0 讨论(0)
  • 2021-02-13 02:19

    There is a Choice Indicator in XML Schema, which allows you to take one of the contained elements, but not two or more. If you want any 2 of 3, I suggest doing something like this:

    <xs:choice>
      <xs:element name="fieldname" type="xs:string" minOccurs="0" maxOccurs="1" />
      <xs:element name="freetext" type="xs:string" minOccurs="0" maxOccurs="1" />
      <xs:element name="dbtablename" type="xs:string" minOccurs="0" maxOccurs="1" />
    </xs:choice>
    <xs:choice>
      <xs:element name="fieldname" type="xs:string" minOccurs="0" maxOccurs="1" />
      <xs:element name="freetext" type="xs:string" minOccurs="0" maxOccurs="1" />
      <xs:element name="dbtablename" type="xs:string" minOccurs="0" maxOccurs="1" />
    </xs:choice>
    

    (Maybe maxOccurs will prevent you from choosing one and the same element twice.) If that does not work, nothing will I think.

    Edited: I didn't correctly understand the question the first time. If you want dbtablename to always be present with any one of fieldname or freetext, then this is the answer:

    <xs:complexType name="tSome">
    <xs:sequence>
      <xs:choice>
        <xs:element name="fieldname" type="xs:string" />
        <xs:element name="freetext" type="xs:string" />
      </xs:choice>
      <xs:element name="dbtablename" type="xs:string" />
    </xs:sequence>
    </xs:complexType>
    
    0 讨论(0)
提交回复
热议问题