XSD: Either/Or syntax
How can i do either/or 开发者_开发问答validation in an XSD? e.g. in the following xml fragment, if the action
is A
(add), then subsequent attributes and elements are required
:
<Post postID="22793" action="A" ...>
<Transaction ...>
<Disposition ...>
<AccountInformation ... />
<ThirdPartyInformation ... />
</Disposition>
<IndividualInformation ... />
</Transaction>
...
</Post>
but if the action is D then subsequent attributes, and attributes, are forbidden::
<Post postID="22793" action="D" />
That is: if the action is delete (D
), then the remaining attributes change from
- required
to
- prohibited
and the subsequent elements switch from
minOccurences="1" maxOccurrences="unbounded"
to
minOccurrences="0" maxOccurrences="0"
Is it possible to use XSD to define xml structure?
One of the big criticisms of XSD is its failure to
...provide no facilities to state that the value or presence of one attribute is dependent on the values or presence of other attributes (so-called co-occurrence constraints).
So it cannot specify constraints like the one you describe. In most circumstances, I've seen projects use XSLT to validate their documents where XSD fails. However other Schema languages do exist, and you may have more success with them. I've heard of some people switching to Relax NG for various reasons.
In XSD version 1.1 now it is possible.
XSD 1.1
The Working Group's strategic guidelines for changes between versions 1.0 and 1.1 can be summarized as follows:
2.Support for co-occurrence constraints (which will certainly involve additions to the XML transfer syntax, which will not be understood by 1.0 processors)
Of course, XPATH 2.0 is being used for assertions on simple and complex types. A new tag is defined for this purpose.
xs:assert
Another useful new mechanism is
Type Alternative components provide associations between boolean conditions (as XPath expressions) and Type Definitions. They are used in conditional type assignment.
xs:alternative
<xs:element name="title" type="xs:anyType">
<xs:alternative test="@type='text'" type="xs:string"/>
<xs:alternative test="@type='html'" type="htmlContentType"/>
<xs:alternative test="@type='xhtml'" type="xhtmlContentType"/>
<xs:alternative test="@type" type="xs:error"/>
<xs:alternative type="xs:string"/>
</xs:element>
You can read more in this
精彩评论