How to specify repeated elements in XSD
Asked Answered
J

1

10

I have a an XSD which validates my XML file. The problem is that it works for one element, but when I have more than one it doesn't work and I can't find the problem.

This is my XML file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <UrlList>
    <url>
        <url>https://www.youtube.com/watch?v=ke92CDVQsb8</url>
        <idUrl>72</idUrl>
        <urlShort>http://short.ly:8080/SOB/url/832261</urlShort>
        <numVisits>2</numVisits>
    </url>
    <url>
        <url>http://moodle.urv.cat/moodle/pluginfil</url>
        <idUrl>73</idUrl>
        <urlShort>http://short.ly:8080/SOB/url/45ea9b</urlShort>
        <numVisits>1</numVisits>
    </url>
</UrlList>

And this is my XSD file:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="UrlList">
        <xs:complexType>
            <xs:sequence>
                <xs:element ref="url"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:element name="url">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="url" type="xs:string"/>
                <xs:element name="idUrl" type="xs:integer"/>
                <xs:element name="urlShort" type="xs:string"/>
                <xs:element name="numVisits" type="xs:integer"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
Joerg answered 2/1, 2015 at 16:12 Comment(0)
T
15

In an <xs:element> inside an <xs:sequence>, if you don't explicitly specify the maxOccurs attribute, it defaults to 1. If you want to be able to have any number of <url> elements inside your <UrlList>, you should change that part of the schema to read as follows:

<xs:element name="UrlList">
    <xs:complexType>
        <xs:sequence>
            <xs:element maxOccurs="unbounded" ref="url"/>
            <!--        ^^^^^^^^^^^^^^^^^^^^^         -->
        </xs:sequence>
    </xs:complexType>
</xs:element>

If you want to only allow, say, 3 <url> elements, use maxOccurs="3" instead, and so forth.

If you instead want to specify that all the elements in the sequence can appear more than once, you can set the maxOccurs attribute on the <xs:sequence> tag instead. It doesn't make a difference in this case, though, because there's only one element in the sequence.

Telles answered 2/1, 2015 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.