Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

xsd - XML schema construct for "any one or more of these elements but must be at least one"

I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements must be present, and there could be more than one of them.

I tried doing the following, but XMLSpy complains that "The content model contains the elements <element name="DateConstant"> and <element name="DateConstant"> which cannot be uniquely determined.":

    <xs:choice>
        <xs:sequence>
            <xs:element name="DateConstant"/>
            <xs:element name="TimeConstant"/>
        </xs:sequence>
        <xs:element name="DateConstant"/>
        <xs:element name="TimeConstant"/>
    </xs:choice>

Can this be done (and if so, how)?

Some clarification: I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either. Gizmo's answer matches my requirements, but it's impractical for a larger number of elements. Hurst's answer allows two or more elements of the same name, which I don't want.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

<xs:choice>
  <xs:sequence>
    <xs:element name="Elem1" />
    <xs:element name="Elem2" minOccurs="0" />
    <xs:element name="Elem3" minOccurs="0" />
  </xs:sequence>
  <xs:sequence>
    <xs:element name="Elem2" />
    <xs:element name="Elem3" minOccurs="0" />
  </xs:sequence>
  <xs:element name="Elem3" />
</xs:choice>

Doing so, you force either to choose the first element and then the rest is optional, either the second element and the rest is optional, either the third element.

This should do what you want, I hope.

Of course, you could place the sub-sequences into groups, to avoid to duplicate an element in each sequence if you realize you miss one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...