XML 1.1 Schema如何约束complexType类型元素的文本内容最少3个字符
报错原因说明
你之前的方案编译不通过的核心原因是:xs:simpleContent 仅适用于没有子元素、仅包含文本内容和属性的complexType定义,你已经通过xs:sequence声明了允许子元素,还设置了mixed="true"支持混合内容,两者定义冲突,所以无法通过编译。
可行解决方案
XML 1.1 环境下主流的 XML Schema 1.1 处理器(如Saxon、Xerces 2 1.1版本)都支持断言功能,可通过xs:assert实现混合内容的文本长度约束,完整示例如下:
<!-- 首先要在schema根节点声明需要XML Schema 1.1支持 --> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1" elementFormDefault="qualified"> <!-- 你用到的condition类型定义示例,按需调整 --> <xs:complexType name="condition"> <xs:attribute name="extended" type="xs:string"/> <xs:attribute name="keyword" type="xs:string"/> </xs:complexType> <xs:element name="text"> <xs:complexType mixed="true"> <xs:sequence> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="condition" type="condition" minOccurs="0" maxOccurs="unbounded"/> <xs:element name="keyword" type="xs:string" minOccurs="0" maxOccurs="unbounded"/> <!-- 其他你允许的子元素定义 --> </xs:choice> </xs:sequence> <xs:attribute name="type" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:enumeration value="question"/> <!-- 其他你允许的属性值枚举 --> </xs:restriction> </xs:simpleType> </xs:attribute> <!-- 核心长度约束规则 --> <xs:assert test="string-length(normalize-space(string(.))) >= 3"/> </xs:complexType> </xs:element> </xs:schema>
规则说明
string(.)会将<text>节点下所有后代文本节点(包括<keyword>这类子元素包含的文本)拼接为完整字符串,如果你仅需要校验<text>直接子级的文本节点、不包含子元素内部文本,把表达式改为string-length(normalize-space(string(text()))) >=3即可normalize-space()会自动去掉首尾空白、将中间连续空白替换为单个空格,避免全是空白字符的内容被误判为有效
如果你的环境只能使用XML Schema 1.0,没有原生支持的混合内容长度校验方案,只能两种方案二选一:
- 调整XML结构,把文本内容单独封装为一个simpleType子元素,对该子元素添加
minLength约束 - 在业务应用层额外做文本长度校验
内容的提问来源于stack exchange,提问作者Daniel Janz
相关产品推荐
相关产品推荐

