Xml Schema for repeating sequence of elements

夙愿已清 提交于 2020-01-02 05:27:50

问题


I have xml as follows

<Search>
    <Term />
    <And />
    <Term />
    <And />
    <Term />
</Search>

There can be n number of Terms and n-1 Ands (n > 0) in the sequence as shown. I tried the following xml schema but above xml would not get validated against the schema. Error: cvc-complex-type.2.4.b: The content of element 'Search' is not complete. One of '{And}' is expected.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="Search">
        <xs:complexType>
            <xs:sequence>               
                <xs:sequence minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="Term" type="xs:string" />
                    <xs:element name="And" type="xs:string" />
                </xs:sequence>              
                <xs:element name="Term" minOccurs="1" maxOccurs="1" type="xs:string" />             
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Appreciate any help with the xml schema.


回答1:


Reordering them like this seems to do it. Am I missing anything?

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="Search">
        <xs:complexType>
            <xs:sequence>
              <xs:element name="Term" minOccurs="1" maxOccurs="1" type="xs:string" />
                <xs:sequence minOccurs="0" maxOccurs="unbounded">
                  <xs:element name="And" type="xs:string" />
                  <xs:element name="Term" type="xs:string" />
                </xs:sequence>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>



回答2:


The revised form of the content model will indeed recognize the language described.

But your XML might be a bit more idiomatic, and would almost certainly be easier to process, if you thought of the XML in terms of the abstract syntax tree you want, rather than in terms of a literal transcription of a surface syntax designed for sequences of tokens rather than trees.

Instead of using an empty And element between terms, wrap the conjunction of terms in an And element.

<Search>
  <And>
    <Term>...</Term>
    <Term>...</Term>
    <Term>...</Term>
  </And>
</Search>

It's now trivially easy to do arbitrary Boolean combinations, without having to worry about what precedence order to ascribe to the operators:

<Search>
  <Or>
    <And>
      <Term>...</Term>
      <Or>
        <Term>...</Term>
        <Term>...</Term>
      </Or>
    </And>
    <And>
       <Term>...</Term>
       <not><Term>...</Term></not>
    </And>
  </Or>
</Search>


来源:https://stackoverflow.com/questions/11059363/xml-schema-for-repeating-sequence-of-elements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!