XSD Tutorials - Herong's Tutorial Examples - Version 5.10, by Dr. Herong Yang
Declaring Complex Elements with Attributes and Sub Elements
This section describes a tutorial example on how to declare an element that accepts attributes and sub (child) elements without text content using a user defined complexType datatype.
A complex element with sub elements and attributes only is an element with sub (child) elements and attributes, but no text content. This type of element can be declared with a "complexType" datatype with "complexContent" containing some "element"s and some "attribute"s.
A good example of complex elements with attributes only is the <table> element in HTML documents. It accepts only attributes like "border" and sub elements like <tr>. But it should not have any text content.
Combine the rules described in the previous two sections, we should be able to define a complex element with sub elements and attributes only by putting the "sequence" of "element" and "attribute" inside "restriction".
Rule 1. The "sequence" of "element" component must be placed before and "attribute" component, if both of them are included in "restriction".
Here is a sample schema, complexType_no_text_content.xsd, that defines <table> to accept sub elements and attributes only, and no text content:
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- complexType_no_text_content.xsd - Copyright (c) 2013, HerongYang.com, All Rights Reserved. --> <xs:element name="table"> <xs:complexType> <xs:complexContent> <xs:restriction base="xs:anyType"> <xs:sequence> <xs:element name="tr" type="xs:anyType" maxOccurs="unbounded"/> </xs:sequence> <xs:attribute name="border" 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_no_text_content.xml <?xml version="1.0"?> <table border="1" note="Tutorials"> <tr><td>Left</td><td>Right</td></tr> <tr><td>Apple</td><td>Orange</td></tr> Example </table> >java XsdSchemaValidator complexType_no_text_content.xsd complexType_no_text_content.xml Error: Line number: 2 Column number: 36 Message: cvc-complex-type.3.2.2: Attribute 'note' is not allowed to appear in element 'table'. Error: Line number: 6 Column number: 9 Message: cvc-complex-type.2.3: Element 'table' cannot have character [children], because the type's content type is element-only. Failed with errors: 2
Last update: 2013.
Table of Contents