Xml Data Binding Tutorial

The following presentation provides a quick overview of what XML Data Binding is and why it's useful.
A text version of the presentation provides more detail and all the source code referenced in the presentation.
(The presentation should take about 2 minutes to read through)

 

 

 

  

 

  • 2 Minute Intro
  • XML & XSD Overview
  • Parsing XML
  • XML Data Binding
  • Example Schema
  • Doing it the Old Way
  • With Data Binding
  • The Generated Code
  • Exploring this Example Yourself
  • More Examples

XML - eXtensible Markup Language.

XML is a text based file format, it allows data to be stored in a tree (hierarchy). Each piece of data is stored along with a label (tag), so it is easy for people to read and understand.

XSD - XML Schema Definition

A schema is a formal description of what can, and can not go into a given XML document (just like a database schema). XSD is just one of several schema specifications, but it is the most widely adopted. The XSD standard has evolved over a number of years, and is controlled by the W3C. It is extremely comprehensive, and as a result has become rather complex - just one of the reasons XML Data Binding is the obvious choice when working with XML documents. Because of this complexity, producing an XML document that complies correctly with its XSD schema is a lot more complex than it may first appear.

Note
designing your XSD schema by hand is extremely difficult, it is strongly recommended that you make use of a graphical tool to author your XSD schemas (See XML Studio, a FREE XSD development tool).

XML DOM Parser - Document Object Model

A DOM parser allows a program to understand an XML document, it reads in the XML, and represents it in memory as a tree of nodes.

The tree produced from the parser is verbose, and generic. Interpreting this tree requires detailed knowledge of the schema. As a result, a lot of code has to be written to create or interpret the content of even a simple DOM tree. Furthermore, the developer writing the coding, needs a very good understanding of the XSD standard (a 400 page standard, which is not easy reading).

Once you start adding more complex schema concepts such as namespace extensions, substitution groups, etc., it can be very tricky to work with, often consuming a large portion a projects development time.

XML Data Binding

Liquid XML reads the XSD (the document description) and uses it to generate a class library in your chosen language (C++, C#, Java, Silverlight 2, VB.Net or Visual Basic 6). You can then incorporate this library within your application in order to manipulate XML documents described by the XSD.

Manipulating your XML documents through this library changes the nature of the task, instead of manipulating a generic unstructured tree of nodes (DOM), you are presented with a hierarchy of structured, strongly typed objects, specifically designed to deal with the data you are working with.
It makes working with your XML data very intuitive, i.e. if you want to change the title of a book - you just set the 'title' property on the 'book' object. It stops the round peg in the square hole problem, using the DOM approach you can create any kind of XML document you want, you could add any element you like to the document (this is a bad thing, putting even a single element/attribute in the wrong place can invalidate the resulting XML document against the rules of its schema). Using the generated library, you can only put elements and attributes in the correct places. The library is in effect a guide, making it impossible to put an element in the wrong place.

In Summary

XML Data Binding short cuts your development effort, simplifies maintenance, increases reliability and thus saves your project time and money throughout its life cycle.

Let's try to create an XML document that conforms to the schema in Figure 1 & Listing 1.

A graphical representation of the schema in Listing 1
(Figure 1 - A graphical representation of the schema)

<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>
(Listing 1 - the source code for the schema)
The common way to do this is using a DOM. I'll use MSXML and VB6 in this example, but the principle is the same in all languages. In java you could use the xerces DOM parser, in C# & VB.Net you could use System.Xml.XmlDocument, and in C++ you could use expat. The code would look very similar in all of them (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
The code above creates the following XML Document. Lots of rather unreadable code to do very 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>

Now let's see the same code written using an XML Data Binding library.

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 

A lot less code, and its much simpler to read. The advantages can be even more obvious when looking at reading in and interpreting XML documents.

<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>

So where does the XML Data Binding library BookStoreSampleLib come from?

The library is generated using Liquid XML Data Binder (part of Liquid XML Studio Developer Edition). It can generate code for C++ , C#, Java, Silverlight 2, VB.Net & Visual Basic 6. The library is generated as source code complete with project files, and you compile it in the usual way for your chosen language. You can also modify the library, adding your own code/methods to it (see hand coded blocks for more information on this).

The Generated Library

The library used in the previous sample is a simple, strongly typed, hierarchy of objects. The structure of this can be seen in this UML diagram.


A UML representation of the class library Generated by Liquid XML

A sample application is generated along side the data binding library. In C# & VB.Net builds, the application makes it possible to browse the structure & properties of the generated XML Data Binding Library. Using the viewer you can also edit the properties and see the effect that this has on the generated XML. This is an extremely effective way of prototyping your code, and is a great way to get to grips with a generated library.

The Sample XSD, Sample XML, Generated code, documentation and object viewer, can be download here (3MB)
To learn more about the Object Viewer Click here.
(The viewer requires the .Net framework to be installed)