XSD唯一属性不起作用

时间:2017-03-26 09:24:21

标签: xml xsd

XSD唯一约束(serverId)不适用于架构:

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

    <xs:complexType name="server">
        <xs:sequence>
            <xs:element name="serverName" type="xs:string"/>
            <xs:element name="port" type="xs:int"/>
            <xs:element name="bossThreadSize" default="2" type="xs:int"/>
            <xs:element name="workGroupSize" default="2" type="xs:int"/>
        </xs:sequence>
        <xs:attribute name="serverId" use="required" type="xs:int"/>
        <xs:attribute name="jarName" use="required" type="xs:string"/>
    </xs:complexType>

    <xs:element name="servers">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="server" type="server" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
        <xs:unique name="uniqueId">
            <xs:selector xpath="tns:server"/>
            <xs:field xpath="@serverId"/>
        </xs:unique>
    </xs:element>

</xs:schema>

我的xml看起来像这样:

<server serverId="1" jarName="frontServer">
    <serverName>FrontServer</serverName>
    <port>3724</port>
    <bossThreadSize/>
    <workGroupSize/>
</server>

<server serverId="1" jarName="frontServer">
    <serverName>FrontServer</serverName>
    <port>3725</port>
    <bossThreadSize/>
    <workGroupSize/>
</server>

因此,虽然两台服务器具有相同的服务器ID,但此xml已成功验证。这有什么不对?

1 个答案:

答案 0 :(得分:1)

您应该声明名称空间前缀tns

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="com.example.whatever"
           elementFormDefault="qualified"
           xmlns:tns = "com.example.whatever">

然后你必须在服务器类型前加上:

<xs:element name="server" type="tns:server" maxOccurs="unbounded"/>