This example illustrates how to use the generated schema wrapper libraries in order to write or read programmatically XML documents conformant to the schema. Before using the sample code, take some time to understand the structure of the schema below.
The schema used in this example describes a library of books. The complete definition of the schema is shown below. Save this code listing as Library.xsd if you want to get the same results as this example. You will need this schema to generate the code libraries used in this example.
<?xml version="1.0" encoding="UTF-8"?>
Library is a root element of a complexType which can be graphically represented as follows in the schema view of XMLSpy:
As shown above, the library has a LastUpdated attribute (defined as xs:dateTime), and stores a sequence of books. Each book is an xs:complexType and has two attributes: an ID (defined as xs:integer), and a Format. The format of any book can be hardcover, paperback, audiobook, or e-book. In the schema, Format is defined as xs:simpleType which uses an enumeration of the above-mentioned values.
Each book also has a Title element (defined as xs:string), as well as one or several Author elements (defined as xs:string).
The library may also contain books that are dictionaries. Dictionaries have the type DictionaryType, which is derived by extension from the BookType. In other words, a dictionary inherits all attributes and elements of a Book, plus two additional elements: FromLang and ToLang, as illustrated below.
The FromLang and ToLang elements store the source and destination language of the dictionary.
An XML instance file valid according to the schema above could therefore look as shown in the listing below (provided that it is in the same directory as the schema file):
<?xml version="1.0" encoding="utf-8"?>
The next topics illustrate how to read from such a file programmatically, or write to such a file programmatically. To begin, generate the schema wrapper code from the schema above, using the steps described in Generating Code from XML Schemas or DTD.