11

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?

Regards

rambius

rambius
  • 131
  • 1
  • 1
  • 4
  • 1
    `minOccurs` should be 1 then – leppie Sep 09 '13 at 09:32
  • 2
    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. – rambius Sep 09 '13 at 09:39

2 Answers2

24

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?

ColdFusion
  • 2,381
  • 13
  • 14
  • Thanks for the info! For reference, here's where that's covered in the XML schema spec: https://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints – hcs Feb 18 '20 at 22:09
-1

call this function

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