问题
I have the following two XML documents:
<struct>
<type>a</type>
<p1 xsi:nil="true"/>
<p2 xsi:nil="true"/>
</struct>
<struct>
<type>b</type>
<p1 xsi:nil="true"/>
<p2 xsi:nil="true"/>
</struct>
I wish to build a schema which validates that in case the value of the element type is "a", then it's sub elements (aka p1
& p2
) should be nil or empty.
Whereas when the element type is something else, such as "b", then p1
or p2
elements can contain anything or nothing.
回答1:
That's a classic example of a "co-occurrence constraint" (the type of one element depends on the value of another). This can't be done with XSD 1.0, but it can be done using XSD 1.1 by means of assertions
<xs:assert test="if (type eq 'a') then nilled(p1) else true()"/>
回答2:
Your XML design is non-ideal.
An element shouldn't be named as generically as struct
if you want to further constrain its contents.
Instead of
<struct>
<type>a</type>
<p1/>
<p2/>
</struct>
use
<a>
<p1/>
<p2/>
</a>
and you'll have no problems writing the XSD.
If you insist on the former form, you'll have to use XSD 1.1's assertion facilities. You can find many examples on this site (or even within an answer just added to this question) of how to write assertions that restrict one element or elements based upon the value of another element.
See also:
- Extend XSD Type based on element value?
- Value of XML element depends on values of other elements in XSD?
- How can allowed element values depend on other element values in XSD?
来源:https://stackoverflow.com/questions/52077040/vary-type-in-xsd-according-to-element-value