Sunday, April 17, 2011

Problem with xml schema elements hierarchy

What's wrong with this xml schema? It doesn't parse correctly, and I can't realize a hierarchy between cluster(element)->host(element)->Load(element).

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="cluster">
    <xs:complexType>
      <xs:sequence>
        <xs:element ref="host"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

  <xs:element name="host">
    <xs:complexType>
      <xs:element ref="Load"/>
      <xs:attribute name="name" type="xs:string" use="required"/>
    </xs:complexType>
  </xs:element>

  <xs:element name="Load">
    <xs:complexType>
      <xs:attribute name="usedPhisicalMemory" type="xs:integer"/>
    </xs:complexType>
  </xs:element>

</xs:schema>

Thank you, Emilio

From stackoverflow
  • In the host element, the load element cannot be a child of complexType, you must have a sequence, etc. in between.

  • To allow something like this (I corrected the typo in "usedPhysicalMemory"):

    <cluster>
      <host name="foo">
        <Load usedPhysicalMemory="500" />
      </host>
      <host name="bar">
        <Load usedPhysicalMemory="500" />
      </host>
    </cluster>
    

    This schema would do it:

    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
      <xs:element name="cluster">
        <xs:complexType>
          <xs:sequence>
            <xs:element ref="host" maxOccurs="unbounded" />
          </xs:sequence>
        </xs:complexType>
      </xs:element>
    
      <xs:element name="host">    
        <xs:complexType>
          <xs:sequence>
            <xs:element ref="Load" />
          </xs:sequence>
          <xs:attribute name="name" type="xs:string" use="required" />
        </xs:complexType>
      </xs:element>
    
      <xs:element name="Load">
        <xs:complexType>
          <xs:attribute name="usedPhysicalMemory" type="xs:integer" />
        </xs:complexType>
      </xs:element>    
    
    </xs:schema>
    

    From the MSDN on <xs:complexType> (because the spec makes my brain hurt):

    If group, sequence, choice, or all is specified, the elements must appear in the following order:

    1. group | sequence | choice | all
    2. attribute | attributeGroup
    3. anyAttribute

    Maybe someone else can point out the relevant section in the spec.

0 comments:

Post a Comment