首页 > 解决方案 > 如何验证嵌套元素中的唯一属性?

问题描述

我有一个这样的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>

标签: xmlxsdnestedunique

解决方案


您应该能够xpath=".//Category"在任何级别使用来选择。

此外,如果约束适用于整个文档,您可以将其放在 ,CategoryDeclaration而不是Category, 以避免在每个类别中进行冗余检查。


推荐阅读