Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSD - allow element type as integer OR empty

Tags:

element

xsd

I need to be able to set a simple element type as an integer but allow it to also be empty. This example sends an error if its empty and a blank field is not an integer. How can I get round this?

<xsd:element name="weight" type="xsd:integer"/>
like image 354
leanne Avatar asked Aug 18 '11 15:08

leanne


4 Answers

What you have to do is assign restrictions on the same element plus make a union on them such as the following example:

<xs:element name="job_code">
  <xs:simpleType>
    <xs:union>
      <xs:simpleType>
        <xs:restriction base='xs:string'>
          <xs:length value="0"/>
        </xs:restriction>
      </xs:simpleType>
      <xs:simpleType>
        <xs:restriction base='xs:integer' />
      </xs:simpleType>
    </xs:union>
  </xs:simpleType>
</xs:element>

By using this restriction, you tell the xml validation to allow any integer value and allowing the element if it is empty.

like image 96
Ahmad Hindash Avatar answered Oct 12 '22 22:10

Ahmad Hindash


We can achieve this by making a SimpleType

<xs:simpleType name="NullOrInteger">
    <xs:restriction base="xs:string">
         <xs:pattern value="\d*|\s{0}" />
    </xs:restriction>
</xs:simpleType>

Add NullOrInteger as the type where you want restriction for an integer or null value.

for example:

<xs:element name="null_or_int" type="NullOrInteger" />
like image 26
krishna pal Avatar answered Oct 12 '22 22:10

krishna pal


You need to set the "nillable" attribute as true:

<xsd:element name="weight" type="xsd:integer" nillable="true"/>

See the XML Schema Primer.

like image 4
parsifal Avatar answered Oct 12 '22 20:10

parsifal


<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!-- Sample XML generated by QTAssistant (http://www.paschidev.com) -->
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <product>
        <weight xsi:nil="true"/>
    </product>
</products>

Try the above, should work; most likely you forgot to add the xsi:nil attribute. Also, make sure that the weight element has no character as children (a white space would still not be acceptable). If you do have to pass some characters instead of an integer, than you have to define a union type to allow for both.

like image 1
Petru Gardea Avatar answered Oct 12 '22 22:10

Petru Gardea