Search code examples
xmlxsdxsd-validationxml-validation

XSD: How to use an element of a type derived from an abstract type correctly?


I have the following schema containing the definition of an abstract list type and the definition of a concrete List type.

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

  <xs:complexType name="BaseListContent" abstract="true" />

  <xs:complexType name="BaseList" abstract="true">
    <xs:sequence>
      <xs:element name="id" type="xs:int" />
      <xs:element name="content" type="BaseListContent" />
    </xs:sequence>
  </xs:complexType>

  <xs:complexType name="ListContent">
    <xs:complexContent>
      <xs:extension base="BaseListContent">
        <xs:sequence>
          <xs:element name="id" type="xs:int" minOccurs="0" maxOccurs="10" />
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:complexType name="List">
    <xs:complexContent>
      <xs:extension base="BaseList">
        <xs:sequence>
          <xs:element name="content" type="ListContent" />
        </xs:sequence>
      </xs:extension>
    </xs:complexContent>
  </xs:complexType>

  <xs:element name="list" type="List" />

</xs:schema>

Now I'm trying to validate the following XML document against the schema:

<list>
  <id>1</id>
  <content>
    <id>1</id>
    <id>2</id>
  </content>
</list>

But xmllint tells me that the document is not valid:

> xmllint --noout --schema ~/test.xsd ~/test.xml
test.xml:1: element list: Schemas validity error : Element 'list': Missing child element(s). Expected is ( content ).
test.xml fails to validate

What is the problem here, as there clearly is a child element content?

Update: a more recent version of xmllint (using libxml version 20904) shows me an error in the schema.

$ xmllint --noout --schema test.xsd test.xml
test.xml:3: element content: Schemas validity error : Element 'content': The type definition is abstract.
test.xml:1: element list: Schemas validity error : Element 'list': Missing child element(s). Expected is ( content ).
test.xml fails to validate

Solution

  • Your XSD itself has a problem even prior to validation of your XML document:

    [Error] test.xsd:23:31: cos-element-consistent: Error for type List. Multiple elements with name content, with different types, appear in the model group.

    The content model for List is an extension of BaseList and so can only add elements, not modify existing elements. Also, same-named but different-typed elements cannot share a parent:

    See also: