nllsdfx
nllsdfx

Reputation: 940

XSD unique attribute is not working

The XSD unique constraint (serverId) is not working for schema:

<?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>

And my xml looks like this:

<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>

So this xml validates successfully though two servers have the same server ids. What is wrong here?

Upvotes: 0

Views: 531

Answers (1)

Kachna
Kachna

Reputation: 2961

You should declare the namespace prefix tns:

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

then you have to prefix the server type:

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

Upvotes: 1

Related Questions