XML特定约束验证求助:全元素值为'N'时XSD验证需失败
<noticeOfEligibility> Child Elements Are 'N' Hey there! Let's work through your XML validation requirement together. You need to ensure the <noticeOfEligibility> element fails XSD validation only if every single one of its child elements has the value 'N'—and passes for any other combination of values. Here's how to make that happen:
Key Background
To implement this custom rule, we'll use XSD 1.1's xs:assert feature, which lets us add logical checks to our schema. Note that XSD 1.0 doesn't support assertions, so you'll need a validator that handles XSD 1.1 (like Saxon 9.x+, Xerces2-J 2.12.0+, or other modern validation tools).
Modified XSD Code
Here's your updated XSD with the validation rule included:
<xs:complexType name="noticeOfEligibility"> <xs:sequence> <xs:element name="displayHCCTable" type="xs:string" /> <xs:element name="displaySNAPTable" type="xs:string" /> <xs:element name="displayTANFTable" type="xs:string" /> <xs:element name="displayCCAPTable" type="xs:string" /> <xs:element name="displayLIHEAPTable" type="xs:string" /> <xs:element name="displayLIHEAPShareTable" type="xs:string" /> <xs:element name="displayEmgyLIHEAPTable" type="xs:string" /> <xs:element name="displayLIHEAPVendorTable" type="xs:string" /> </xs:sequence> <!-- Assertion to enforce the validation rule --> <xs:assert test="not(every $child in * satisfies $child = 'N')" /> </xs:complexType>
How It Works
The assertion expression not(every $child in * satisfies $child = 'N') does exactly what we need:
every $child in * satisfies $child = 'N'checks if all child elements of<noticeOfEligibility>have the value 'N'.- Wrapping that in
not(...)reverses the logic: when all children are 'N', this condition becomesfalse, so validation fails. For any other combination (even one non-'N' value), the condition istrue, and validation passes.
Testing the Rule
- Your provided XML example (all child elements set to 'N') will fail validation as expected.
- If you change even one element to a different value (e.g.,
<displayHCCTable>Y</displayHCCTable>), the XML will pass validation.
内容的提问来源于stack exchange,提问作者Manoj Chauhan

