在xsd单个字段上添加唯一约束

2024-04-27 04:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下xml。你知道吗

 <Movies>
     <Title>
         <Platform>Hulu</Platform>
         <PlatformID>50019855</PlatformID>
         <UnixTimestamp>1431892827</UnixTimestamp>
     </Title>
     <Title>
         <Platform>Hulu</Platform>
         <PlatformID>50019855</PlatformID>
         <UnixTimestamp>1431892127</UnixTimestamp>
     </Title>
 </Movies>

然后我有以下xsd来验证上述内容:

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

<xs:element name="Movies">
  <xs:complexType>
    <xs:sequence>
      <xs:element name="Title" maxOccurs="unbounded">
        <xs:complexType>
          <xs:sequence>
            <xs:element name="Platform" type="xs:string"/>
            <xs:element name="PlatformID" type="xs:string"/>
            <xs:element name="UnixTimestamp" type="xs:positiveInteger"/>
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
</xs:element>
</xs:schema>

我该如何添加一个惟一约束,使得PlatformID是惟一的值,并且如果存在重复的值(例如在上面的xml中),验证就会失败?你知道吗


Tags: namestringtitleschematypexmlelementmovies
1条回答
网友
1楼 · 发布于 2024-04-27 04:14:00

您需要将xs:unique常量放在Movies级别内,而不是放在Title级别内。如果它在Title级别内,它将只检查该节点内的重复项:

XML格式

<Movies>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID>
        <UnixTimestamp>1431892827</UnixTimestamp>
    </Title>
    <Title>
        <Platform>Hulu</Platform>
        <PlatformID>50019855</PlatformID>
        <UnixTimestamp>1431892127</UnixTimestamp>
    </Title>
</Movies>

XSD公司

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="Movies">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Title" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="Platform" type="xs:string"/>
                            <xs:element name="PlatformID" type="xs:string" maxOccurs="unbounded"/>
                            <xs:element name="UnixTimestamp" type="xs:positiveInteger"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
        <xs:unique name="uniquePlatformID">
            <xs:selector xpath=".//Title/PlatformID"/>
            <xs:field xpath="."/>
        </xs:unique>
    </xs:element>
</xs:schema>

相关问题 更多 >