xml - 如何验证嵌套元素中的唯一属性?
问题描述
我有一个这样的xml:
<?xml version="1.0" encoding="utf-8"?>
<CategoryDeclaration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Category CategoryId="1" DislayText="CategoryName1">
<Category CategoryId="123" DislayText="CategoryName2">
<ErrorType DislayText="text1" ErrorTypeId="123" />
<ErrorType DislayText="text2" ErrorTypeId="222" />
</Category>
</Category>
<Category CategoryId="1" DislayText="CategoryName1">
<ErrorType DislayText="text2" ErrorTypeId="222" />
</Category>
</CategoryDeclaration>
属性 CategoryId 和 ErrorTypeId 在整个 xml 文件中应该是唯一的,但不要让它工作。类别元素可以无限嵌套。
这是我的 xsd,仅适用于同一级别的元素:
<?xml version="1.0" encoding="utf-16"?>
<xsd:schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="qualified">
<xsd:element name="Category">
<xsd:complexType mixed="true">
<xsd:choice minOccurs="1" maxOccurs="unbounded">
<xsd:element ref="Category" minOccurs="0" />
<xsd:element ref="ErrorType" minOccurs="0" />
</xsd:choice>
<xsd:attribute name="CategoryId" use="required" type="xsd:integer" />
<xsd:attribute name="DislayText" use="required" type="xsd:string" />
</xsd:complexType>
<xsd:unique name="UniqueCategoryId">
<xsd:selector xpath="Category" />
<xsd:field xpath="@CategoryId" />
</xsd:unique>
</xsd:element>
<xsd:element name="ErrorType">
<xsd:complexType mixed="true">
<xsd:attribute name="ErrorTypeId" use="required" type="xsd:integer" />
<xsd:attribute name="DislayText" use="required" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="CategoryDeclaration">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Category" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
解决方案
您应该能够xpath=".//Category"
在任何级别使用来选择。
此外,如果约束适用于整个文档,您可以将其放在 ,CategoryDeclaration
而不是Category
, 以避免在每个类别中进行冗余检查。
推荐阅读
- angular - 使用锯齿状数组在 TypeScript 中格式化硬编码的 json 对象
- ios - BlackBerry Dynamics SDK iOS v. 8.0 崩溃应用
- html - 我正在尝试在标题处添加背景图像,为什么它不会显示?
- python - Pytorch GPU 利用率
- ruby - Ruby Restclient 不同的双点或 astrophobe 并且顺序很重要
- python - 继承中的赋值类型不兼容 - Mypy 错误
- ios - Swift 中的 Alamofire 和 ObjectMapper 到 TableView
- linux - Linux,重击。检测 USB 设备数据传输是否处于活动状态
- java - Apache Avro - Avro 地图值中的复杂类型
- android - 滚动到另一个页面后,ViewPager 中的视图不可见