XML Data Binding

XML Data Binding

Contents

  • What Is XML Data Binding?: An introduction to the technology.
  • Products: A summary of the products currently available
  • Functional Summary: A summary of what these products are capable of
  • In Detail: A more in-depth look at what is produced when code is generated from a schema

What Is XML Data Binding?

XML Data Binding allows you to manipulate an XML document via a set of simple objects. The rules defining the 'shape' of the XML document are described in an XML schema. Typically, it is possible to read an XML document into an XML binding library and manipulate it programmatically via simple get and set methods. Conversely, a document can be created from an XML data binding library, and serialized as an XML document.

Still not clear? Well, look at the benefits.

A Simple Example

Try to create an XML document that conforms to the schema in Figure 1a.

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            elementFormDefault="qualified">
   <xsd:element name="bookstore" type="bookstoreType" />
   <xsd:complexType name="bookstoreType">
      <xsd:sequence maxOccurs="unbounded">
         <xsd:element name="book" type="bookType" />
      </xsd:sequence>
   </xsd:complexType>
   <xsd:complexType name="bookType">
      <xsd:sequence>
         <xsd:element name="title"  type="xsd:string" />
         <xsd:element name="author" type="authorName" />
         <xsd:element name="price"  type="xsd:decimal" />
      </xsd:sequence>
      <xsd:attribute name="genre"           type="xsd:string" />
      <xsd:attribute name="publicationdate" type="xsd:string" />
      <xsd:attribute name="ISBN"            type="xsd:string" />
   </xsd:complexType>
   <xsd:complexType name="authorName">
      <xsd:sequence>
         <xsd:element name="first-name" type="xsd:string" />
         <xsd:element name="last-name"  type="xsd:string" />
      </xsd:sequence>
   </xsd:complexType>
</xsd:schema>

Figure 1a

To see a graphic depiction, see Figure 1b.

The obvious way to do this is by using a DOM. I'll use MSXML and VB6 as an example; see Figure 2.

Dim oXmlDoc As MSXML2.DOMDocument40
Dim oElmBookStore As MSXML2.IXMLDOMElement
Dim oElmBook As MSXML2.IXMLDOMElement
Dim oAttrGenre As MSXML2.IXMLDOMAttribute
Dim oAttrPublicationDate As MSXML2.IXMLDOMAttribute
Dim oAttrISBN As MSXML2.IXMLDOMAttribute
Dim oElmBookTitle As MSXML2.IXMLDOMElement
Dim oElmBookAuthor As MSXML2.IXMLDOMElement
Dim oElmBookAuthorFirstName As MSXML2.IXMLDOMElement
Dim oElmBookAuthorLastName As MSXML2.IXMLDOMElement
Dim oElmBookPrice As MSXML2.IXMLDOMElement

' create the document
Set oXmlDoc = New MSXML2.DOMDocument40

' Create the document element
Set oElmBookStore = oXmlDoc.createElement("bookstore")
oXmlDoc.appendChild oElmBookStore

' Add the first book
Set oElmBook = oXmlDoc.createElement("book")
oElmBookStore.appendChild oElmBook

' add genre attribute
Set oAttrGenre = oXmlDoc.createAttribute("genre")
oElmBook.Attributes.setNamedItem oAttrGenre
oAttrGenre.Value = "autobiography"

' add publicationdate attribute
Set oAttrPublicationDate =
   oXmlDoc.createAttribute("publicationdate")
oElmBook.Attributes.setNamedItem oAttrPublicationDate
oAttrPublicationDate.Value = "1981"

' add publicationdate attribute
Set oAttrISBN = oXmlDoc.createAttribute("ISBN")
oElmBook.Attributes.setNamedItem oAttrISBN
oAttrISBN.Value = "1-861003-11-0"

' Add Title to book
Set oElmBookTitle = oXmlDoc.createElement("title")
oElmBook.appendChild oElmBookTitle
oElmBookTitle.nodeTypedValue = "The Autobiography of Benjamin _
                                Franklin"

' Add Author to book
Set oElmBookAuthor = oXmlDoc.createElement("author")
oElmBook.appendChild oElmBookAuthor

' Add the first name attributes to the author
Set oElmBookAuthorFirstName = oXmlDoc.createElement("first-name")
oElmBookAuthor.appendChild oElmBookAuthorFirstName
oElmBookAuthorFirstName.nodeTypedValue = "Benjamin"

' Add the last name attributes to the author
Set oElmBookAuthorLastName = oXmlDoc.createElement("last-name")
oElmBookAuthor.appendChild oElmBookAuthorLastName
oElmBookAuthorLastName.nodeTypedValue = "Franklin"

' Add Price to book
Set oElmBookPrice = oXmlDoc.createElement("price")
oElmBook.appendChild oElmBookPrice
oElmBookPrice.nodeTypedValue = "8.99"

' output the XML we created
Debug.Print oXmlDoc.xml

Figure 2

The code in Figure 2 creates the XML Document in Figure 3. Lots of code to do so little!

<bookstore>
   <book genre="autobiography" publicationdate="1981"
         ISBN="1-861003-11-0">
      <title>The Autobiography of Benjamin Franklin</title>
      <author>
         <first-name>Benjamin</first-name>
         <last-name>Franklin</last-name>
      </author>
      <price>8.99</price>
   </book>
</bookstore>

Figure 3

Now, see the same code written by using an XML Data Binding library (see Figure 4). I'll cover the details of where the XML Binding library comes from later.

Dim oElmBookStore As New BookStoreSampleLib.Bookstore
Dim oElmBook As BookStoreSampleLib.Book

' create a new book
Set oElmBook = oElmBookStore.Books.Add

' populate the book
oElmBook.Genre            = "autobiography"
oElmBook.PublicationDate  = "1981"
oElmBook.ISBN             = "1-861003-11-0"
oElmBook.Title            = "The Autobiography of Benjamin Franklin"
oElmBook.Author.Firstname = "Benjamin"
oElmBook.Author.Lastname  = "Franklin"
oElmBook.Price            = 8.99

' output the XML we created
Debug.Print oElmBook.xml

Figure 4

Just a bit less code, and it's much simpler to maintain. And, the advantages can be even more obvious when looking at reading in and interpreting XML documents.

So, where does the XML data binding library BookStoreSampleLib come from? A tool generates it for you. There are a number of different tools on the market at the moment, and each goes about the job of turning an XML schema into an object orientated library a little differently.

XML Data Binding

Products

There are many products on the market, and if your schema is very simple and you're using Java, Castor is probably your best bet. There are already a number of good Castor articles out there and I don't intend to rehash them. However, if you are not a Java developer, or your schema contains more advanced features (extensions, restrictions, substitution groups, and so forth), you will need to look a little farther afield. I have reviewed the main products on the market, and produced a simple summary of their capabilities. For the remainder of this article, I will refer to the generator provided by Liquid Technologies because it supports the major schemas (DTD, XDR, and XSD) and the main languages (C#, VB6, Java, and cross platform C++).

There are also a number of important things to take into account when selecting a suitable product (free is not always cost cheap).

User Created Schemas

If you are designing your own schema, you're in a position to tailor your schema to work around any limitations in the data binding product you select. Because of this, even a fairly limited binding product can be expected to produce working code if the schema contains constructs that it can deal with. However, this approach may result in you compromising the design of your schemas, forcing you to use very simple constructs and types. These compromises may ultimately impact on the development of your project.

Third-Party Schemas

The choice of products is more important when dealing with standard schemas. The problem with standard schemas is you're not in a position to change them; you sometimes can tweak the way in which they are written, but you can't change their meaning. So, imagine you start off using a standard schema, and use a product such as JAXB, which initially works well. Later, the next version of the schema is released, and it makes use of more of the XSD standard (say, extensions), and now JAXB won't work any more. What do you do?

You're more or less back to square one. Your only real option is to go and look for a product that does support your new schema, but this will mean re-factoring all your existing code. So, it would be better to select a product that provides a large amount of support up front.

This section contains a review of the functionality supported by a number of the main XML Data Binding products.

Product Install Size Ease of Install Getting started Ease of Use Quality of Output Cost Overall Rating Comments (at a glance, see below for a full review)
Castor   6 3 3 62% Open Source 5 Getting up and and running with Castor was a real pain. It can generate Java code for simple schemas. The code produced is straightforward and works reasonably well
JAXB 46MB 8 7 7 55% ? 6 JAXB installs as part of Sun's web development toolkit. The install is simple and, if you have JDK 1.4 installed, trouble free.
A batch file is provided, making it simple to use. Unfortunately, JAXB fails to cope with anything more than the very basic XSD schemas.
Liquid Technologies XML Data Binding 11MB 9 8 9 87% $495 8.5 The XML Data Binding wizard installation is simple. Generating code is simple; you use a basic wizard. The product can output code for Java, C#, VB6, and C++ (Win32, Solaris, and Linux), and is capable of coping with the majority of the XSD standard.
Microsoft's xsd.exe N/A N/A 5 7 61% N/A 6 Installs with Visual Studio .NET. The command line interface makes it a little bit annoying to work with. It copes with a good percentage of the XSD standard, but provides no validation, and still requires the user to have an good understanding of the target XSD.

Functionality Summary

Gen: Generates code for schema's with these features
Sup: Supports these features correctly in the code that is created.

Product Castor JAXB Liquid Tech Xsd.exe
Languages Supported
C# (.NET)
Java
C++ (Win32, Linux, Solaris)
Visual Basic 6
VB.NET (.NET)

Product Castor JAXB Liquid Tech Xsd.exe
  Gen Sup Gen Sup Gen Sup Gen Sup
ComplexType groups
Sequence *1, *5
Choice *4
All *5
Multiple Models, same complextype *1, *5
Types
Hex/Base64
Date/Time/gMonthDay etc. *2 *2
Collections of primitives *13
All primitive data types *18, *19 *18 *18 *18
unions *2 *2 *2
any
anyAttribute
default values
Pad chars (&<>" etc.) N/A N/A N/A N/A
Strongly Typed Output N/A N/A *23 N/A N/A *10
Facets
fractionDigits
length
maxExclusive *20 *18
minExclusive *20 *18
maxInclusive *20
minInclusive *20
maxLength
minLength
pattern   *9
totalDigits
whiteSpace
Cardinality
Optional *17 *5
Mandatory *5
Multiple *5, *11
Enumerations
Enumerated Attributes *14 *22 *3
Enumerated Elements *14 *22 *3
0-n Enumerated Elements *14, *15 *22 *3
Documentation
Documentation Generation *21 *21 *21 *21
Include comments from Schema
complexContent
extension
restriction *7 ?
Different base model types ?
Schema
Namespace
Import ?
Include ?
Groups
Recursively defined elements
substitutionGroups
Invalid names for the language
Elements & attributes with same name ?
Mixed elements *8 *8 *8 *8
                 
TOTAL 87% 62% 75% 55% 97% 87% 86% 61%

*1 No validation is done on the order that the elements are in
*2 Treated as strings
*3 Only applies on strings
*4 A choice with 0 or many elements is falsely accepted
*5 No validation is done to ensure mandatory fields are populated
*6 Ignores elements that are valid substitution elements
*7 Allows child elements that have been restricted
*8 Can't handle mixed content (like HTML <H1>text<B>more text</B>Some More Text</H1> 'text' & 'Some More Text' get misrepresented; typically concatenated)
*9 Supported on some data types
*10 Choices, and some uses of extension cause un-typed objects to be returned
*11 It is possible to produce invalid XML output
*12 Elements are missing from the output
*13 Strange bug whereby it invented two unsigned Byte elements with arbitrary values where only 1 is declared in the XML
*14 Enumerations that are not based on strings, are named badly (value0, value1, value2, and so on)
*15 No validation is done when setting values
*16 No validation is done when reading XML
*17 No support for optional groups (in other words, an optional sequence or choice)
*18 All data types are supported but the validation rules are not applied to all of the types
*19 Many primitive types are not supported, resulting in code that does not compile (ENTITY, ENTITIES, name, token, UnsignedLong UnsignedInt, UnsignedShort, UnsignedByte)
*20 Using facets on some data types (in other words, gDay) causes the output code to be invalid (not compile)
*21 Creates JavaDoc comments
*22 Enumerated types are supported but treated as primitives (no validation is performed)
*23 Collections are not strongly typed

XML Data Binding

Castor (0.9.5)

Castor is one of the first tools of its type. It provides XML and DB data binding for the Java framework. Before you start, I should point out that I have only investigated the XML Data Binding functionality.

Castor is capable of accepting XSD files, and generates the source code for a Java library that allows serialization to and from XML. The generated code relies on xerces as its XML parser.

The code generated is split; one class is generated to hold information contained in an XML element, and a second class is generated to handle the marshaling to and from XML. This split has the advantage to keeping the memory footprint small, but does cause a large number of classes to be generated!

Castor is attractive to developers because it is Open Source, and seems pretty well thought out. It is, however, far from complete; there are a number of classes and areas of functionality missing. Because of this, it copes well with simple schemas, but is unable to cope with the complexities of many of the real-world standards.

Limitations include:

  • No support for extending elements (extension and restriction)
  • No support for substitution groups
  • No support for namespaces
  • Patchy support for primitive data types (name, token, ENTITY, and the like are not supported)
  • Patchy support for facets

In Summary: Castor is a good choice when working with simple schemas; it has a strong following and is still being improved. It is, however, still a work in progress, sporting an awkward command line interface. Eventually, it may be a smart choice, but at the moment it is still maturing. It is useful on small schemas that you have direct control over. Try to use this with an externally controlled schema, and you're asking for trouble in the long run, when they add in features that Castor just can't deal with.

JAXB

JAXB is provided by Sun as part of their web development toolkit (I believe this makes it free, but I am unceratin of the exact terms of their license; check Sun's end user license).

JAXB is something of a half-hearted attempt, but is capable of generating Java code for very basic schemas. However, give it any real work and it chokes.

Limitations include:

  • No support for extending elements (extension and restriction)
  • No support for external elements (any, anyType)
  • No support for enumerated elements
  • Collections are not strongly typed
  • Does not work with Web Logic

In Summary: If the product you select has to be free, use Castor. Otherwise, there is little reason to use JAXB.

Liquid Technologies: XML Data Binding Wizard (3.1)

The Liquid Technologies solution is one of the most complete products available, with almost complete support for XSD, XDR. and DTD schemas. It also has the advantage of generating code for a number of platforms an languages—C#, Java, VB6, C++ (for Win32, Linux, HP, and Solaris). It also produces a full set of documentation (CHM and HTML) for the generated class library, making development simpler.

This product is ideal for dealing with both industry standard and hand-made schemas. It is the only system currently available that is reliable enough to use on an evolving industry standard because it is the only generator on the market that supports so much of the XSD standard.

Limitations include:

  • No validation on restrictions
  • No validation on unions

In Summary: This is the most complete system on the market (at the time of writing), making it ideal for user defined and industry standard schemas. The code generated is clean and easy to use, and the generated documentation is a bonus.

This is, however, a commercial product, and as such needs paying for ($495). That said, it should pay for itself within the week!

Xsd.exe (1.0.3705.0.)

Microsoft have taken a very minimal approach to their generator. The classes (C# or VB.Net) that are generated just contain public member variables that map to the XSD's attributes and elements, no accessors, no methods, nothing. The XML serialization is carried out by external libraries that come with the .NET framework. These classes use the attribute data (the stuff in square brackets) that is declared within each of the generated classes.

The generated classes allow many features of the XSD standard to be supported; however, they provide practically no validation. They are quite happy to read in almost any XML, and will try to fit it into the generated objects. This is a significant limitation, but it can be mitigated by first reading the data into a validating XML DOM (validating against the schema), before loading it into the generated object model; this, of course, costs CPU cycles. Furthermore, it is all too easy to populate objects that are themselves not valid against the schema; again, this can be addressed by validating the output XML against the schema by using a validating DOM parser.

Other significant shortfalls in this generator include:

  • A lack of support for namespaces
  • Substitution groups
  • A lack of support for nested groups (sequences containing choices and so on)
  • Optional items with default values can't be excluded from the output XML
  • All classes are generated into the same file; larger XSDs can become a little unmanageable
  • Choices are represented as an untyped item that can be cast to the appropriate type. When the type is ambiguous, a ItemsElementName property is created; the name of this enumeration is ItemsChoiceTypeX, making it difficult to pick the correct one for an element

In summary, the Microsoft offering is an elegant solution to the problem; the decision to avoid validation should make its code generation robust. However, it is still unable to cope with a large number of XSD features that occur in many real-world schemas. This makes it unfit for use on large, complex schemas, especially if you don't have the ability to change the schema yourself. It is however, free and simple to use, making it ideal for small projects in which you get to describe your own schemas.

In Detail

As you have already seen, using the code generated from a data binding tool can greatly reduce the amount and complexity of the code you have to write when dealing with XML. If you have a complex schema and are not an XSD expert, the benefits are clear.

In this next section, you will look at the code produced for a number of XSD constructs. I have chosen C# as the language because it is simpler to read; however, the output for Java, C++, and VB6 all take the same form, and the code required to use the generated code is almost identical (once the syntax of the languages is taken into account).

Elements Examined

  • Sequence
  • Choice
  • Primitive and Complex Types
  • Cardinality
  • Extension

Sequence

A sequence describes an element and defines that all child elements must appear (if mandatory) and they must appear in the correct order.

Sample XSD

<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">
   <xs:element name="ParentSeq">
      <xs:complexType>
         <xs:sequence>
            <xs:element name="FirstChild"  type="Xs:string" />
            <Xs:element name="SecondChild" type="Xs:string" />
            <Xs:element name="ThirdChild"  type="Xs:string" />
         </Xs:sequence>
      </Xs:complexType>
   </Xs:element>
</Xs:schema>

Code

// create an instance of the class to load the XML file into
SequenceLib.ParentSeq elm = new SequenceLib.ParentSeq();
// Set data into element
elm.ThirdChild  = "Some Data 3";
elm.FirstChild  = "Some Data 1";
elm.SecondChild = "Some Data 2";
// Let's see what we've got
Trace.WriteLine(elm.ToXml());

Xml Created

<?xml version="1.0"?>
<!--Created by Liquid XML Data Binding Libraries
(www.liquid-technologies.com) for simon-->
<ParentSeq xmlns:Xs="http://www.w3.org/2001/XMLSchema-instance">
   <FirstChild>Some Data 1</FirstChild>
   <SecondChild>Some Data 2</SecondChild>
   <ThirdChild>Some Data 3</ThirdChild>
</ParentSeq>

Notes

  • It does not matter the order in which the child elements are set. They will appear correctly in the output XML.
  • If the child elements are not in the correct order when an XML file is read in, an exception is raised.
  • The element all works in the same way as sequence. The elements are written out in the order they were defined, but when they are read in, they can be in any order.

Choice

A choice describes an element, and defines that only one of the child elements can appear.

Sample XSD

<?xml version="1.0" encoding="UTF-8" ?>
<Xs:schema xmlns:Xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">
   <Xs:element name="ParentSeq">
      <Xs:complexType>
         <Xs:choice>
            <Xs:element name="FirstChild"  type="Xs:string" />
            <Xs:element name="SecondChild" type="Xs:string" />
            <Xs:element name="ThirdChild"  type="Xs:string" />
         </Xs:choice>
      </Xs:complexType>
   </Xs:element>
</Xs:schema>

Code—reading from a file

// create an instance of the class to load the XML file into
choiceLib.ParentChoice elm = new choiceLib.ParentChoice();
elm.FromXmlFile("c:\\Choice.xml");
// we can find out child child element is selected by using
// ChoiceSelectedElement
if (elm.ChoiceSelectedElement == "SecondChild")
{
   Trace.Write("The second child element was present and has the
                value " + elm.SecondChild);
}
// or by looking at the IsValid flags
Debug.Assert(elm.IsValidFirstChild  == false);
Debug.Assert(elm.IsValidSecondChild == true);
Debug.Assert(elm.IsValidThirdChild  == false);

Note

If more than one child element is selected in the XML, the FromXmlFile will raise an exception..

Primitive and Complex Types

You've now covered how the basic constructs (all/sequence/choice) are represented. However, all the child items used have all been of type string. This section will explore other types, and show how other more complex child elements can be manipulated.

Sample XSD

<?xml version="1.0" encoding="UTF-8" ?>
<Xs:schema xmlns:Xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">
   <Xs:element name="RootElm">
      <Xs:complexType>
         <Xs:sequence>
            <Xs:element name="StringType" type="Xs:string" />
            <Xs:element name="intType"    type="Xs:int" />
            <Xs:element name="ComplexType">
               <Xs:complexType>
                  <Xs:sequence>
                     <Xs:element name="DateType"
                                 type="Xs:dateTime" />
                     <Xs:element name="Base64Type"
                                 type="Xs:base64Binary" />
                  </Xs:sequence>
               </Xs:complexType>
            </Xs:element>
         </Xs:sequence>
      </Xs:complexType>
   </Xs:element>
</Xs:schema>

Classes Created

public class RootElm : LiquidTechnologies.LtXmlLib3.XmlObjectBase
{
   public String StringType { get... set...}
   public Int32 IntType { get... set...}
   public TypesLib.ComplexType ComplexType { get... set...}
}
public class ComplexType :
   LiquidTechnologies.LtXmlLib3.XmlObjectBase
{
   public LiquidTechnologies.LtXmlLib3.XmlDateTime DateType
      { get... set...}
   public LiquidTechnologies.LtXmlLib3.BinaryData Base64Type
      { get... set...}
}

Code—reading from a file

// create an instance of the class to load the XML file into
TypesLib.RootElm elm = new TypesLib.RootElm();
// set data into the element
elm.StringType = "Test String value";
elm.IntType = 5;
// and the child element
elm.ComplexType.DateType.SetDateTime(2004, 4, 26, 10, 41, 35);
elm.ComplexType.Base64Type.SetData("075BCD15",
                                   BinaryData.Encoding.Hex);
// Let's look at the XML we produced.
Trace.WriteLine(elm.ToXml());

XML Produced

<?xml version="1.0"?>
<!--Created by Liquid XML Data Binding Libraries
    (www.liquid-technologies.com) for simon-->
<RootElm xmlns:Xs="http://www.w3.org/2001/XMLSchema-instance">
   <StringType>Test String value</StringType>
   <intType>5</intType>
   <ComplexType>
      <DateType>2004-04-26T10:41:35</DateType>
      <Base64Type>cLXcUQ==</Base64Type>
   </ComplexType>
</RootElm>

Note

If the ComplexType held within the RootElm was optional, you would have to create and assign an object to elm.ComplexType before using it (see next item).

XML Data Binding

Cardinality

In this sample, the sequence contains a number of child elements. The child elements all have different cardinalities (changed by setting the minOccurs and maxOccurs attributes; the default for both is 1). The generator deals with these flags in three different ways.

Mandatory: minOccurs=1 and maxOccurs=1

If the child element is a primitive (string, short time, and so forth), a get and set accessor is provided. The value held must always contain a valid (non null) value.

If the child element is another complex element (in other words, represented as new class in the generated code), a get accessor is provided. This will always return a valid object.

Optional: minOccurs=0 and maxOccurs=1

If the child element is a primitive (string, short time, and so on), a get and set and IsValid accessor is provided. While IsValid is true, the value held must always contain a valid (non null) value. If IsValid is set to false, the get accessor will fail if called, and no child element is created in the XML.

If the child element is another complex element (in other words, represented as new class in the generated code), a get and set accessor is provided. This will initially be null. If the child element is required in the XML, a new child object must be created (new XXX()), and assigned to the property. It can be removed by setting the value to null.

Collection: minOccurs=n and maxOccurs= >1

If the child element is a primitive (string, short time, and the like), a get accessor is provided. The object returned from the get operator is a collection of primitive types. If the collection is empty, no items appear in the XML.

If the child element is another complex element (in other words, represented as new class in the generated code), a get accessor is provided. This returns an object that represents a collection of the complex elements.

Sample XSD

<?xml version="1.0" encoding="UTF-8" ?>
<Xs:schema xmlns:Xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">
   <Xs:element name="Cardinality">
      <Xs:complexType>
         <Xs:sequence>
            <Xs:element name="MandatoryChild" type="Xs:string" />
            <Xs:element name="OptionalChild" type="Xs:string"
                        minOccurs="0" />
            <Xs:element name="CollectionChild" type="Xs:string"
                        minOccurs="0" maxOccurs="unbounded" />
         </Xs:sequence >
      </Xs:complexType>
   </Xs:element>
</Xs:schema>

Code

// create an instance of the class to load the XML file into
CardinalityLib.Cardinality elm = new CardinalityLib.Cardinality();
// Write data into the element
elm.MandatoryChild = "Some value";
// set some data into the optional element
elm.OptionalChild = "Some other data";
// if we change our mind we can remove this element from the output
elm.IsValidOptionalChild = false;
// The collection element contains a child collection
// (the collection is always populated)
elm.CollectionChild.Add("First item in collection");
elm.CollectionChild.Add("Second item in collection");
// Let's look at the XML we've just created
Trace.WriteLine(elm.ToXml());
// Reading from the element
Trace.Write("Mandatory element contains value - " + 
            elm.MandatoryChild);
if (elm.IsValidOptionalChild == true)
   Trace.Write("Optional element present. Value - " +
               elm.OptionalChild);
else
   Trace.Write("The optional element is not present");
   Trace.Write("Child elements in the Collection element");
foreach(string val in elm.CollectionChild)
   Trace.Write("    value - " + val);

Xml Created

<?xml version="1.0"?>
<!--Created by Liquid XML Data Binding Libraries
    (www.liquid-technologies.com) for simon-->
<Cardinality xmlns:Xs="http://www.w3.org/2001/XMLSchema-instance">
   <MandatoryChild>Some value</MandatoryChild>
   <CollectionChild>First item in collection</CollectionChild>
   <CollectionChild>Second item in collection</CollectionChild>
</Cardinality>

Note

You use the IsValidOptionalChild property to determine whether the OptionalChild element was present in the XML.

Extension

A base complex type can be extended. The concept is similar to that of inheritance in C#, C++, Java, and so forth. In this sample, you define a base complex type "BaseComplexType", and derive from it two other complex types: "DerivedComplexType1" and "DerivedComplexType2".

Finally, you define an element, UsingElement, that contains an element of type "BaseComplexType". In this element, wherever you see "BaseComplexType", you can use either "DerivedComplexType1" or "DerivedComplexType2".

Sample XSD

<Xs:schema xmlns:Xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified"
           attributeFormDefault="unqualified">
   <Xs:complexType name="BaseComplexType">
      <Xs:sequence>
         <Xs:element name="ChildOfBaseType" type="Xs:string" />
      </Xs:sequence>
   </Xs:complexType>
   <Xs:complexType name="DerivedComplexType1">
      <Xs:complexContent>
         <Xs:extension base="BaseComplexType">
            <Xs:sequence>
               <Xs:element name="ChildOfDerivedType1"
                           type="Xs:string" />
            </Xs:sequence>
         </Xs:extension>
      </Xs:complexContent>
   </Xs:complexType>
   <Xs:complexType name="DerivedComplexType2">
      <Xs:complexContent>
         <Xs:extension base="BaseComplexType">
            <Xs:sequence>
               <Xs:element name="ChildOfDerivedType2"
                           type="Xs:string" />
            </Xs:sequence>
         </Xs:extension>
      </Xs:complexContent>
   </Xs:complexType>
   <Xs:element name="UsingElement">
      <Xs complexType >
         <Xs:sequence>
            <Xs:element name="BaseType" type="BaseComplexType"/>
         </Xs:sequence>
      </Xs complexType >
   </Xs:element>
</Xs:schema>

Code

// create an instance of the class to load the XML file into
ExtensionLib.UsingElement elm = new ExtensionLib.UsingElement();

//////////////////////////////////////
// Write Data into the new element
// Use the element DerivedComplexType2 in the base element
// UsingElement.BaseType where a BaseComplexType is exected
ExtensionLib.DerivedComplexType2 elmDerv2 =
   new ExtensionLib.DerivedComplexType2();
elmDerv2.ChildOfBaseType = "Data field From Base";
elmDerv2.ChildOfDerivedType2 = "Data field From Derived Class";
elm.BaseType = elmDerv2;

// Look at the XMl we just created
Trace.WriteLine(elm.ToXml());

//////////////////////////////////////
// Read data from the element
// The object we get from elm.BaseType is exposed via an interface
// common to all the objects that can be used in its place
// (IBaseComplexType).
Trace.WriteLine("Data from the Base class -
   " + elm.BaseType.ChildOfBaseType);

// The actual object held in elm.BaseType can be either
// DerivedComplexType1, DerivedComplexType2 or BaseComplexType
// we need to use runtime type info to find out.
if (elm.BaseType.GetType().Name == "DerivedComplexType2")
{
   // now we know the type, we can cast it up accordingly
   ExtensionLib.DerivedComplexType2 elmDerv =
      (ExtensionLib.DerivedComplexType2)elm.BaseType;
   // and then make use of the properties defined in the derived
   // class
   Trace.WriteLine("Data in DerivedComplexType2.ChildOfDerivedType2
      class - " + 
   elmDerv.ChildOfDerivedType2);
}

Xml Created

<?xml version="1.0"?>
<!--Created by Liquid XML Data Binding Libraries
    (www.liquid-technologies.com) for simon-->
<UsingElement xmlns:Xs="http://www.w3.org/2001/XMLSchema-instance">
   <BaseType Xs:type="DerivedComplexType2">
      <ChildOfBaseType>Data field From Base</ChildOfBaseType>
      <ChildOfDerivedType2>
         Data field From Derived Class
      </ChildOfDerivedType2>
   </BaseType>
</UsingElement>


Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

  • The first phase of API management was about realizing the business value of APIs. This next wave of API management enables the hyper-connected enterprise to drive and scale their businesses as API models become more complex and sophisticated. Today, real world product launches begin with an API program and strategy in mind. This API-first approach to development will only continue to increase, driven by an increasingly interconnected web of devices, organizations, and people. To support this rapid growth, …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds