¿Cómo definir un valor predeterminado para un elemento de opción usando XSD?

What I like to do: I want to specify an option tag in the schema, for example:

<xsd:element name="my_element" type="my_type" minOccurs="0" maxOccurs="1"/>

If the element does not occur at all, there should be a default value for this parameter. Of course I could define this default value in my code, which calls the XML parser. But I think the correct place to specify the default value would be in the *.xsd schema file (since the default value is part of the interface defined by the schema).

Unfortunately this does not seem to be easy. The "default" attribute has a different effect: "if it does not appear it is not provided; if it does appear and it is empty, its value is the default value" (from http://www.w3.org/TR/xmlschema-0/#ref36).

Other links I've found discussing this issue:

Is there a solution to this problem? Or should I give up?

preguntado el 13 de febrero de 14 a las 13:02

1 Respuestas

simple elements may have a default value OR a fixed value specified.

A default value is automatically assigned to the element when no other value is specified.

In the following example the default value is "red":

<xs:element name="color" type="xs:string" default="red"/>

A fixed value is also automatically assigned to the element, and you cannot specify another value.

In the following example the fixed value is "red":

<xs:element name="color" type="xs:string" fixed="red"/>

Respondido 13 Feb 14, 13:02

If I add an element in the XML without value it can have a default value. But my problem: I need a default value if the element is not at all available in the XML file. I use it for backward compatibility in a config file. - lúmbrico

@lumbric: You can use a minOccurs=0 attribute on the element in your schema and you will get an empty or null value, depending on the parser. But to get the default value, the element debe: appear without another value. Pretty stupid and painful shortcoming for a language so heavily used, but we all have to deal with that. Bottom line: handle it in your application. - Suncat2000

@jtyreman: Thanks for the extra information about fixed frente a default. Rare but useful in the right situation. - Suncat2000

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.