alexearp
alexearp

Reputation: 1

I keep getting xs:key is invalid, misplaced, or occurs to often

I'm new to programing and I need help using xs:key in XML Schema. I've been given an XML for which I have to create an XML Schema. I've managed to complete all the parts correctly. However, the attribute numSerie needs to work as an identifier and I can't get xs:key to work. This is the full XML Schema:

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

    <xs:simpleType name="tipoNumSerie">
        <xs:restriction base="xs:string"/>
    </xs:simpleType>

        <xs:key name="idNumSerie">
                <xs:selector xpath="impresora"/>
                <xs:field xpath="@numSerie"/>
        </xs:key>
    
    <xs:complexType name="tipoImpresora">
        <xs:sequence>
            <!--List of simple elements-->                                                                                                                
        </xs:sequence>  
            <xs:attribute name="numSerie" type="tipoNumSerie"/>             
    </xs:complexType>

    <xs:complexType name="tipoImpresoras">
        <xs:sequence>                           
            <xs:element name="impresora" type="tipoImpresora" maxOccurs="unbounded"/> 
        </xs:sequence>
    </xs:complexType>

    <xs:element name="impresoras" type="tipoImpresoras"/>

</xs:schema>

I get this error message "s4s-elt-invalid-content.1: The content of 'schema' is invalid. Element 'key' is invalid, misplaced, or occurs too often.xsd(s4s-elt-invalid-content.1)"

I tried moving the xs:key from that position to a position right under <xs:attribute name="numSerie" type="tipoNumSerie"/>, as some websites specified, but it didn't work.

I'd appreciate it if someone could help me a bit on this because I got stuck. Thanks in advance!

Upvotes: 0

Views: 41

Answers (2)

Michael Kay
Michael Kay

Reputation: 163577

The general rule is this: if you want every X within a Y to have a unique value for Z, then the xs:key element should be a child of the element declaration of Y, its xs:selector should select X starting from Y, and its xs:field should select Z starting from X.

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167716

Place the xsl:key inside of the parent element of impresora e.g. impresoras:

    <xs:element name="impresoras" type="tipoImpresoras">
        <xs:key name="idNumSerie">
                <xs:selector xpath="impresora"/>
                <xs:field xpath="@numSerie"/>
        </xs:key>
    </xs:element>

Upvotes: 1

Related Questions