Schematron规则引擎:声明式XML业务约束验证
利用ISO Schematron编写基于模式(pattern)和断言(assert)的业务规则,对XML文档进行上下文敏感的非结构验证。 · 难度:入门 · +10XP
Schematron规则引擎:声明式XML业务约束验证
XML Schema只能验证结构和数据类型,无法表达如“当订单类型为国际时,地址必须包含国家代码”之类的交叉字段业务规则。Schematron使用XPath编写断言规则,无需额外编程语言。本教程从最基础的assert/report元素开始,展示如何用抽象模式(abstract pattern)参数化验证规则以减少重复。然后讲解规则分类:通过phase属性为不同验证场景(如录入阶段、审批阶段)启用不同规则集。最后教授如何将Schematron嵌入Ant或Maven构建流程,以及如何生成人类可读的错误报告(包含中文消息和XPath定位)。
<schema xmlns="http://purl.oclc.org/dsdl/schematron">
<pattern>
<rule context="order">
<assert test="@type != 'international' or address/country">
国际订单必须包含国家代码
</assert>
</rule>
</pattern>
</schema>