0
votes

How can I restrict the cardinality of the param element when it has no attributes? I want it to have a max occurence of 1 (it behaves at app level as default param) So this is valid

<xml>
    <param>value</param>
    <param id="1">value</param>
    <param id="2">value</param>
    <param id="3">value</param>
</xml>

but this is not

 <xml>
    <param>value</param>
    <param>value2</param>
    <param id="1">value</param>
    <param id="2">value</param>
    <param id="3">value</param>
</xml>

So far, I tried with

a definition of both a param xs:element with no attirbute specified and another with attribute specified, wrapped within a xs:choice. But it does not allow me to use two elements with the same name

1
Can you modify your XML source in any way? Adding an attribute, for example?helderdarocha
Well this is more a theoretical question, I could add "default" attribute. Perhaps it's a matter of bad practice.Whimusical

1 Answers

1
votes

If you are designing the schema, it would be best to have a <param> with a different name, since it is a different thing after all. In XSD 1.0, elements with the same names should contain represent the same types. If it had an id attribute with a fixed value, you could use an uniqueness constraint (which would also affect the other param elements) restricting any elements with the same id. That would also limit its occurrence to 0 or 1.

If you can't change the XML, an alternative is to use a parser with XSD 1.1 support. In XSD 1.1 you can have alternative types for the same elements. You can also use assertions to enforce rules using XPath, for example using a test like count(param[not(@id)]) <= 1 in the context of the parent node:

<xs:complexType>
    <xs:sequence>
        <xs:element name="param" maxOccurs="unbounded">...</xs:element>
    </xs:sequence>
    <xs:assert test="count(param[not(@id)]) le 1" />
</xs:complexType>