Karen Tsirunyan
Karen Tsirunyan

Reputation: 1998

Correct way to define elements with xsd:all

I am new to xml and I am trying to understand the xsd:all element. As MSDN says:

xsd:all allows the elements in the group to appear (or not appear) in any order in the containing element.

So, as I understand if we make a simple example of xsd schema:

  <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" >  
    <xsd:element name = "MyElem">
     <xsd:complexType>
            <xsd:all>
            <xsd:element name = "name" type = "xsd:string" />
            <xsd:element name = "lastname" type = "xsd:string" />
            <xsd:element name = "city" type = "xsd:string" />
            </xsd:all>
     </xsd:complexType>
    </xsd:element>
  </xsd:schema>

then we can have an xml file like this:

<MyElem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Example.xsd" >
    <name>"some_name"</name>
    <lastname>"some_last_name"</lastname>
    <city>"somecity"</city>          
</MyElem>

This is pretty clear. But when I try to give to MyElem no elements, as there is mentioned in definition (allows elements appear or not appear), I get error in xml file, which says:

following elements are expected at this location.

I am using Altova xmlSpy xml editor.

Does I understood correctly that elements may or may not appear in the containing element?

Thank you for help.

Upvotes: 0

Views: 48

Answers (1)

C. M. Sperberg-McQueen
C. M. Sperberg-McQueen

Reputation: 25054

If you want some elements to be optional, give them minOccurs="0". To specify that name, lastname, and city may all occur in any order, with city being optional:

<xsd:all>
  <xsd:element name = "name" type = "xsd:string" />
  <xsd:element name = "lastname" type = "xsd:string" />
  <xsd:element name = "city" type = "xsd:string" minOccurs="0"/>
</xsd:all>

Upvotes: 1

Related Questions