如何将Schematron规则添加到XSD文件中实现Customer属性校验?
问题核心原因
XSD的xsd:import/xsd:include指令仅支持引入同规范的XSD结构定义文件,Schematron属于独立于XSD的业务规则校验规范,无法直接通过XSD原生导入语法集成。目前业界有两种通用落地方案:
方案一:XSD内嵌Schematron规则(推荐,和现有XSD体系绑定最紧密)
直接将Schematron规则写入customer.xsd的xsd:annotation/xsd:appinfo节点中,无需额外维护独立规则文件,修改后的customer.xsd如下:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.test.com/customer" xmlns:cust="http://www.test.com/customer" xmlns:sch="http://purl.oclc.org/dsdl/schematron"> <!-- 新增Schematron命名空间声明 --> <xsd:complexType name="customerType"> <xsd:annotation> <xsd:appinfo> <!-- 内嵌Schematron规则 --> <sch:pattern id="customerTypeCheck"> <sch:rule context="cust:customerType"> <!-- 修正原规则语法错误:test后补等号,同时修正规则逻辑和提示对应:@type <=10时触发校验失败 --> <sch:assert test="@type > 10">Customer的type属性值必须大于10,当前值为<sch:value-of select="@type"/></sch:assert> <sch:report test="@type > 100">Customer的type属性值超过100,当前值为<sch:value-of select="@type"/></sch:report> </sch:rule> </sch:pattern> </xsd:appinfo> </xsd:annotation> <xsd:sequence> <xsd:element name="Name" type="xsd:string" /> <xsd:element name="Address" type="xsd:string" /> <xsd:element name="Phone" type="xsd:string" /> <xsd:element name="email" type="xsd:string" /> </xsd:sequence> <xsd:attribute name="type" type="xsd:integer" /> </xsd:complexType> </xsd:schema>
支持嵌入Schematron的校验工具(如 Saxon、Oxygen XML、Xerces 扩展包)会自动读取XSD中嵌入的规则,一次校验即可同时完成XSD结构校验和Schematron业务规则校验。
方案二:独立Schematron文件两步校验
如果希望规则和XSD结构解耦,可以修正你现有Schematron文件的语法、命名空间问题后,先跑XSD校验,再跑Schematron校验:
修正后的Schematron规则文件(customer.sch)
<?xml version="1.0" encoding="UTF-8"?> <!-- 修正原命名空间拼写错误:ocle改为oclc --> <sch:schema xmlns:sch="http://purl.oclc.org/dsdl/schematron" queryBinding="xslt2" xmlns:cust="http://www.test.com/customer" xmlns:po="http://www.test.com/po"> <sch:pattern> <!-- 匹配PurchaseOrder下的Customer元素 --> <sch:rule context="po:PurchaseOrder/*:Customer"> <!-- 补全test后的等号,修正规则提示逻辑 --> <sch:assert test="@type > 10">Customer的type属性值必须大于10,当前值为<sch:value-of select="@type"/></sch:assert> <sch:report test="@type > 100">Customer的type属性值超过100,当前值为<sch:value-of select="@type"/></sch:report> </sch:rule> </pattern> </sch:schema>
校验流程
- 先用原XSD集群完成order.xml的结构合法性校验
- 再用Schematron校验工具加载上述sch文件完成业务规则校验
内容的提问来源于stack exchange,提问作者Meric Ozcan
相关产品推荐
相关产品推荐

