问题
Consider two possible implementations of a "tag group":
Authors are allowed to use either an element named <tag-group>
or any element with attribute role="tag-group"
.
I'd like to write an XSD schema that will validate either case.
Ideally, the schema can also validate that children are valid within a given parent. The "tag group", for example, allows children to be either an element named <tag>
or any element with attribute role="tag"
.
So the ideal schema would validate, that given <tag-group>
, the child should be <tag>
; OR given any element with role="tag-group"
, the child should be any element with role="tag"
.
Test case expectations:
PASS
<tag-group>
<tag>foo</tag>
</tag-group>
PASS
<foo role="tag-group">
<bar role="tag">fum</bar>
</foo>
FAIL
<tag-group>
<bar role="tag">fum</bar>
</tag-group>
FAIL
<foo role="tag-group">
<tag>foo</tag>
</foo>
I am new to XSD and happy to look through reference docs if you link them.
回答1:
The farther you get from type being defined by element name, the more you'll find yourself generally going against the grain of XSD.
XSD 1.1's Conditional Type Assignment (CTA) allow the content model to vary per attribute values. XSD 1.1's assertions allow further type variations based on data dependencies. You can try to craft assertions for such additional type "flexibility", but I'll caution you that there quickly comes a point where it's better to rethink your design.
See also for CTA:
- How to make type depend on attribute value using Conditional Type Assignment
- XSD 1.1 Conditional Type Assignment <alternative test=""> to check if an element hasn't an attribute set?
来源:https://stackoverflow.com/questions/60553803/xsd-define-element-by-name-or-alternate-attribute