XML Schema Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.00

Declaring Complex Elements with Attributes, Sub Elements and Text Content

This section describes a tutorial example on how to declare an element that accepts attributes and sub (child) element mixed with text content using a user defined complexType datatype.

A complex element with text content, sub elements, and attributes can be declared with a "complexType" datatype with "complexContent mixed="true"" containing some "element"s and some "attribute"s.

A good example of complex elements with attributes only is the <form> element in HTML documents. It accepts attributes like "action", sub elements like <input>, and text contents.

Rule 1. The "mixed="true"" attribute inside "complexContent" allows text content to be mixed in the element.

This rule should be used with other rules described in previous sections to define a complex element with text content, sub elements, and attributes.

Here is a sample schema, complexType_everything.xsd, that defines <form> to accept sub elements attributes, and text content:

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- complexType_everything.xsd
 - Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
-->

 <xs:element name="form">
 <xs:complexType>
  <xs:complexContent mixed="true">
   <xs:restriction base="xs:anyType">
    <xs:sequence>
    <xs:element name="input" type="xs:anyType" maxOccurs="unbounded"/>
    </xs:sequence>
    <xs:attribute name="action" type="xs:string"/>
   </xs:restriction>
  </xs:complexContent>
 </xs:complexType>
 </xs:element>

</xs:schema>

Let's try this schema on a sample XML document, complexType_no_text_content.xml, with some errors:

>type complexType_everything.xml

<?xml version="1.0"?>
<form action="submit.pl" note="Tutorials">
 Your Name: <input type="text"/>
 <input type="submit"/>
</form>


>java XsdSchemaValidator complexType_everything.xsd 
   complexType_everything.xml

Error:
   Line number: 2
   Column number: 43
   Message: cvc-complex-type.3.2.2: Attribute 'note' is not
   allowed to appear in element 'form'.

Failed with errors: 1

Sections in This Chapter

Complex Element vs. Simple Element

Declaring Empty Elements

Declaring Simple Elements

Declaring Complex Elements with Simple Content

Declaring Complex Elements with Attributes Only

Declaring Complex Elements with Sub Elements Only

Declaring Complex Elements with Attributes and Sub Elements

Declaring Complex Elements with Attributes, Sub Elements and Text Content

Using Shorthand for "complexContent" with "restriction"

Dr. Herong Yang, updated in 2007
Declaring Complex Elements with Attributes, Sub Elements and Text Content