基于Section元素Id属性的XML验证方法及问题咨询
基于Section元素Id属性的XML验证方案
首先先把你提供的XML代码格式化出来,方便后续讨论:
<Sections> <Section Id="DateAndTimeSection" Enable="True" > <Column Id="Date" Format="YYYYMMDD" /> <Column Id="Time" Format="HHMMSS" /> </Section> <Section Id="ComponentIdSection" Enable="True" > <Column Id="ComponentId" Title="COUNTER" Enable="True" /> </Section> </Sections>
从你提到的“基于Section元素的Id属性验证”来看,我先覆盖几种最常见的验证需求,你可以对应自己的场景参考:
一、用XSD Schema做结构化强验证(最规范的方式)
如果需要强制Section的Id只能是预定义的有效值,并且不同Id的Section要对应特定的子元素规则,可以编写如下XSD:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Sections"> <xs:complexType> <xs:sequence> <xs:element name="Section" maxOccurs="unbounded"> <xs:complexType> <xs:sequence> <xs:element name="Column" maxOccurs="unbounded"> <xs:complexType> <xs:attribute name="Id" type="xs:string" use="required"/> <xs:attribute name="Format" type="xs:string"/> <xs:attribute name="Title" type="xs:string"/> <xs:attribute name="Enable" type="xs:boolean"/> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Id" use="required"> <xs:simpleType> <!-- 限定Section的Id只能是以下预定义值 --> <xs:restriction base="xs:string"> <xs:enumeration value="DateAndTimeSection"/> <xs:enumeration value="ComponentIdSection"/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name="Enable" type="xs:boolean" use="required"/> </xs:complexType> <!-- 针对不同Id的Section做针对性子元素验证 --> <xs:assert test="if (@Id='DateAndTimeSection') then count(Column[@Id='Date' and @Format] and Column[@Id='Time' and @Format])=2 else true()"/> <xs:assert test="if (@Id='ComponentIdSection') then count(Column[@Id='ComponentId' and @Title='COUNTER'])=1 else true()"/> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </Sections>
这个XSD实现了这些验证逻辑:
- 强制Section的
Id是必填项,且只能是DateAndTimeSection或ComponentIdSection - 针对不同Id的Section,验证子Column是否符合要求(比如
DateAndTimeSection必须包含带Format属性的Date和Time列) - 定义了所有元素属性的基本类型约束
你可以用支持XSD 1.1的工具(比如Oxygen XML Editor、Java的javax.xml.validation API)来验证你的XML文档。
二、用XPath做快速自定义验证
如果只是需要快速检查某些Id相关的规则,比如:
- 检查所有Section的Id是否唯一:
返回count(//Section[@Id]) = count(//Section[@Id][not(.=preceding::Section/@Id)])true则表示所有Id都是唯一的。 - 检查是否存在指定Id的Section:
boolean(//Section[@Id='DateAndTimeSection']) - 检查
DateAndTimeSection下的列是否符合格式要求:boolean(//Section[@Id='DateAndTimeSection']/Column[@Id='Date' and @Format='YYYYMMDD'] and //Section[@Id='DateAndTimeSection']/Column[@Id='Time' and @Format='HHMMSS'])
你可以在XML编辑器、浏览器开发者工具或者代码中执行这些XPath表达式完成验证。
三、如果你的需求更具体?
你提到的“当Id值……”内容被截断了,如果是要验证Id的格式(比如必须以Section结尾)、Id对应的Section有其他特殊规则,可以补充说明细节,我再给你调整验证方案。
内容的提问来源于stack exchange,提问作者Alif Meerasahib
相关产品推荐
相关产品推荐

