tags:

views:

221

answers:

4

I have a XML defining properties like :

<properties>
    <property name="play_sound" value="true" />
    <property name="duration" value="30" />
</properties>

Is it possible, with an XML schema, specify conditions such as "if the property name is 'duration' then the value must be an integer". I think it is not possible so, what is the recommended way to model that kind of information in a XML file?

I have been thinking about something like:

<properties>
    <play_sound>true</play_sound>
    <duration>30</duration>
</properties>

That way I can define type restrictionos in my schema. But, what happens if I have hundreds of different properties, that are likely to grow in the future...?

Thank you.

+1  A: 

I don't think you can enforce this by property name. You could probably do something with Schematron though.

There's a general trade-off between verbose strict schema vs. relaxed compact schema. You'll have to decide what's better in your situation based on what the XML file is used for and how the Xsd is being used.

Ben Lings
+1  A: 

There is no conditional support in XSD to do what you want. Is it absolutely critical for you to have your XML validated by the parser?

If so, your only options are defining properties as types (like you've described) or as attributes (e.g. <my_object play_sound="true" duration="30"/>)

Usually, however, it does not matter if the validation occurs at a later stage (when your XML is digested by your application, for example) at which point it's easy enough to do what you want.

ChssPly76
+1  A: 

XML Schema 1.0 does not have these sorts of constraints.

XML Schema 1.1, which is currently in development, does.

If you use the Saxon XSLT/XQuery engine, there is an early implementation of XML Schema 1.1 included for experimentation.

Another option is to use Schematron.

But typically, these are handled inside of the application. XML Schema is fair at describing the structure of the data, but not so good at actually validating the content.

lavinio
+1  A: 

The recommended way would be to model your XML with specific attributes or elements that have specific types.

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
    <xs:element name="properties">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="play_sound" type="xs:boolean"/>
                <xs:element name="duration" type="xs:byte"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

<properties>
    <play_sound>true</play_sound>
    <duration>30</duration>
</properties>
John Saunders