Schematron 规则模式与上下文跳跃验证(abstract/context/assert/report)
学习 Schematron 中的抽象规则、多级上下文切换以及结合 XPath 2.0 进行复杂语义验证,超越 DTD/XSD 的能力。 · 难度:入门 · +10XP
Schematron 规则模式与上下文跳跃验证
Schematron 基于断言而非结构约束,可以验证元素之间的关系。本教程首先对比 assert(必须为真)与 report(为真则报告)的用法,然后讲解 context 属性如何设置当前检验节点。深入抽象规则(abstract rule)配合 extends 实现规则复用,以及如何利用 XPath 2.0 的序列操作、函数如 current() 进行跨祖先验证。最后展示一个复杂事例:验证文档中所有引用的 ID 对应的元素类型必须符合预期。
<schema xmlns='http://purl.oclc.org/dsdl/schematron'>
<pattern>
<rule context='order'>
<assert test='count(customerRef) = 1'>每个订单必须有一个客户引用</assert>
<report test='not(customerRef = //customer/@id)'>引用的客户 ID 不存在</report>
</rule>
</pattern>
</schema>