问题
According to this page (and my practice), xs:group
element cannot be child of xs:all
.
So something like
<xs:group name="g">
<xs:element name="first" type="xs:string"/>
<xs:element name="last" type="xs:string"/>
</xs:group>
<xs:all>
<xs:group ref="g" minOccurs="0" maxOccurs="1"/>
<xs:element name="id" type="xs:string"/>
</xs:all>
is not valid because group cannot be inside xs:all
. But I want to define a schema, in which two elements (first
and last
in above example) both exist or neither of them exists, so I make them into a group. Then I want to make the group part of xs:all
because the group can appear with other elements (for example, id element above) in any order. In other words, I want to have several elements are optional as a whole group. Without xs:group
being able to be child of xs:all
, how can I achieve this?
回答1:
XML Schema 1.0 only permits xs:element
(and xs:annotation
) under xs:all
.
<all
id = ID
maxOccurs = 1 : 1
minOccurs = (0 | 1) : 1
{any attributes with non-schema namespace . . .}>
Content: (annotation?, element*)
</all>
It does not allow xs:group
, xs:sequence
, xs:choice
etc.
XML Schema 1.1 permits xs:element
, xs:any
, or xs:group
under xs:all
:
<all
id = ID
maxOccurs = (0 | 1) : 1
minOccurs = (0 | 1) : 1
{any attributes with non-schema namespace . . .}>
Content: (annotation?, (element | any | group)*)
</all>
Note: Allowing unordered elements may sound ideal but rarely is truly needed. Usually xs:sequence
suffices in practice.
If you are willing to forgo the unordered requirement, you could (even in XSD 1.0) require first
and last
to "both exist or neither of them exist" as follows:
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a">
<xs:complexType>
<xs:sequence>
<xs:sequence minOccurs="0">
<xs:element name="first" type="xs:string"/>
<xs:element name="last" type="xs:string"/>
</xs:sequence>
<xs:element name="id" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
来源:https://stackoverflow.com/questions/33698600/xml-schema-why-xsgroup-cant-be-child-of-xsall