# XSD: valor predeterminado de un elemento faltante

Is it possible to define a default value for a missing element in an XML Schema. I have the following snippet:

<xs:element name="protocol" nillable="false" minOccurs="0" default="ftp">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="ftp"/>
<xs:enumeration value="webdav"/>
</xs:restriction>
</xs:simpleType>
</xs:element>


If I have in the XML file

<protocol>ftp</protocol>


or

<protocol>webdav</protocol>


it validates and I obtain the right value. If I have in the XML file

<protocol></protocol>


it also validates and I obtain the default value of ftp.

My searches show that default attribute values apply when attributes are missing, and default element values apply when elements are empty. Is it possible to have a default value for a missing element?

saludos

rambius

preguntado el 09 de septiembre de 13 a las 10:09

minOccurs should be 1 then -

I want the protocol element to be optional, but if missing, it should be ftp. It looks like it is not possible and I should handle that logic in the application, not in the schema. -

## 2 Respuestas

No. XSD doesn't provide for that.

You can specify the default value of an element. But once it is missing (when that's allowed by the content model of its parent), any requests to that element will return either empty string or null (or just an error). The missing element is non-existent element!

For attributes it is possible, because attributes are far simpler. All attributes of an element effectively constitute an unordered set of named simple values. There is no some kind of attribute tree (with the variable structure at that) attached to the parent element.

But with elements things are far more complex. If something "default" about missing elements were allowed, that would cause lots of ambiguities. For instance, some kind of "default content" would have to be specified then, which would be some sequence of elements evoked automatically in place of emptiness... or even a number of possible "default contents" each evoked when only some elements are specified explicitly and others must supplement them implicitly (by default). .... Well, if you think further on, the things are getting mind-boggling complex. Another language would have to be created then! But for what purpose?

Respondido el 09 de Septiembre de 13 a las 11:09

Thanks for the info! For reference, here's where that's covered in the XML schema spec: w3.org/TR/xmlschema-0/#OccurrenceConstraints - HCS

llamar a esta función

def _get_(x):
if x is not None:
return(x.text)
else:
# print('Setting Blank')
return ''
_get_(parent.find('childtag'))


Respondido el 17 de Septiembre de 19 a las 18:09

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