1

我有一个带有以下关联 xsd 的 xml 文件:

元素 ContentTitle 必须是唯一的。我已经进行了一些调查并且知道使用 xs:unique 属性,但是我还没有让它在我的场景中正常工作。

任何人都可以提供建议吗?

  <xs:element name="AllMeta">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="WikiMeta">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ContentTitle" type="xs:string" minOccurs="1" maxOccurs="1" />
              <xs:element name="PageTitle" type="xs:string" minOccurs="1" maxOccurs="1" />
              <xs:element name="PageMetaDescription" type="xs:string" minOccurs="1" maxOccurs="1" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
4

1 回答 1

0

在for之后添加一个xs:unique元素:xs:complexTypeAllMeta

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="AllMeta">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="WikiMeta">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="ContentTitle" type="xs:string" minOccurs="1" maxOccurs="1" />
              <xs:element name="PageTitle" type="xs:string" minOccurs="1" maxOccurs="1" />
              <xs:element name="PageMetaDescription" type="xs:string" minOccurs="1" maxOccurs="1" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
    <xs:unique name="uniqueContentTitle">
      <xs:selector xpath="WikiMeta"/>
      <xs:field xpath="ContentTitle"/>
    </xs:unique>    
  </xs:element>
</xs:schema>

然后,这个 XML 文档实例将是有效的:

<?xml version="1.0" encoding="UTF-8"?>
<AllMeta xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="try.xsd">
  <WikiMeta>
    <ContentTitle>One</ContentTitle>
    <PageTitle></PageTitle>
    <PageMetaDescription></PageMetaDescription>
  </WikiMeta>
  <WikiMeta>
    <ContentTitle>Two</ContentTitle>
    <PageTitle></PageTitle>
    <PageMetaDescription></PageMetaDescription>
  </WikiMeta>
</AllMeta>

并且这个 XML 文档实例将是无效的:

<?xml version="1.0" encoding="UTF-8"?>
<AllMeta xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="try.xsd">
  <WikiMeta>
    <ContentTitle>One</ContentTitle>
    <PageTitle></PageTitle>
    <PageMetaDescription></PageMetaDescription>
  </WikiMeta>
  <WikiMeta>
    <ContentTitle>One</ContentTitle>
    <PageTitle></PageTitle>
    <PageMetaDescription></PageMetaDescription>
  </WikiMeta>
</AllMeta>

验证器(在本例中为 Xerces-J)将给出如下错误消息:

[Error] try.xml:10:37: cvc-identity-constraint.4.1: Duplicate unique value [One] declared for identity constraint "uniqueContentTitle" of element "AllMeta".
c:/gd/usr/kjh/proj/try/xsd/try.xml: 219 ms (9 elems, 1 attrs, 0 spaces, 49 chars)
于 2013-10-22T11:40:25.783 回答