问题
I'm trying to do some specific stuff in an XSD XML Schema. I want to set an element as use="required"
, only if there a specific value to an attribute of another element.
Example:
<udi att1="all">
<name att2="dsd"/>
<phone att3="dsd"/>
</udi>
I want the phone
element to be required, only if the att1
value is all
.
I was told that XPath could work for this - or is there a better way?
回答1:
XML is not relational, it's hierarchical. Schemas are designed to enforce rules on nesting, not on rules between siblings. It simply is not something you can do with XSD.
You can do it when you're parsing or creating documents conforming to the format, however. In this case, while you're parsing through the XML document, you enforce constraints like the one you have stated in your question.
回答2:
For posterity: this requirement can be achieved:
(a) by using new features in XSD 1.1 (assertions, conditional type assignment)
(b) by using Schematron for validation alongside XSD.
来源:https://stackoverflow.com/questions/511148/how-to-make-use-attribute-required-optional-depend-on-another-value