login | register    

XML Data Binding Example with source code for C++, C#, Java & Visual Basic

Overview

This example will show the code generated produced from a simple schema. Along with sample code showing how to use it to read and write a simple XML Document.

Also included in the download is the simple object viewer. This allows you to explorer a generated class library, and is an excellent tool for prototyping, and evaluating the generated output.

The Schema

We will generate the class libraries using the following XSD. This is done using the XML Data Binding Wizard.

Examples - Source Code From XSD
A Full Example - Including all Source
Source Code from <xs:all>
Source Code from <xs:choice>
Source Code from <xs:sequence>
Effects of Cardinality (min/maxOccurs)
Effects of <xs:extension>
How Different Types are Dealt With

          
         The source & generated sample code.

 

<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:date"/>
        <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 - The code for our sample XSD schema)


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

The Sample XML File

The following sample XML will be used for the following examples

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

The Generated Output

Expand each section to see a summary of the generated code, including sample code showing how to read and write an XML document. Note this is the simplified version of the source, all comments, private and protected methods have been removed for clarity. The full source code can be download.

Generated C# Classes

Write Sample

Code

   // to create the XML document from scratch
    BookStoreLib.Bookstore bs = new BookStoreLib.Bookstore();
    BookStoreLib.BookType book = bs.Book.Add();
    book.Title = "The Autobiography of Benjamin Franklin";
    book.Price = 8.99;
    book.Publicationdate = new LtXmlLib4.XmlDateTime(1981, 5, 11);
    book.ISBN = "1-861003-11-0";
    book.Author.First_name = "Benjamin";
    book.Author.Last_name = "Franklin";
    book.Genre = "autobiography";
    string strXml = book.ToXml();
    System.Console.WriteLine(strXml);

Output

Read Sample

Code

// to create the XML document from scratch
    BookStoreLib.Bookstore bs = new BookStoreLib.Bookstore();
    bs.FromXmlFile(@"BookStoreSample.xml");
    foreach (BookStoreLib.BookType book in bs.Book)
    { 
        System.Console.WriteLine("Book Title           {0}", book.Title);
        System.Console.WriteLine("    Price            {0}", book.Price);
        System.Console.WriteLine("    Author           {0} {1}", 
        book.Author.First_name, book.Author.Last_name);
        if (book.IsValidPublicationdate)
            System.Console.WriteLine("    Publicationdate  {0}", book.Publicationdate.ToString());
        else                    
            System.Console.WriteLine("    Publicationdate  Not Listed");
        if (book.IsValidISBN)
            System.Console.WriteLine("    ISBN             {0}", book.ISBN);
        else                    
            System.Console.WriteLine("    ISBN             Not Listed");
        if (book.IsValidGenre)
            System.Console.WriteLine("    Genre            {0}", book.Genre);
        else                    
            System.Console.WriteLine("    Genre            Not Listed");
    }

Output

Generated Code

BookStore.cs

namespace BookStoreLib
{
    public class Bookstore  : LiquidTechnologies.LtXmlLib4.XmlGeneratedClass
    {
        public Bookstore()
... public Bookstore(String elementName) ... public override object Clone() ... #region Attribute - book public BookStoreLib.BookTypeCol Book { get { return m_Book; } } protected BookStoreLib.BookTypeCol m_Book; #endregion #region Attribute - Namespace public override String Namespace { get { return "; } } #endregion // ##HAND_CODED_BLOCK_START ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS // Add Additional Methods and members here... // ##HAND_CODED_BLOCK_END ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS } }

BookType.cs

namespace BookStoreLib
{
    public class BookType  : LiquidTechnologies.LtXmlLib4.XmlGeneratedClass
    {
        public BookType()
... public BookType(String elementName) ... public override object Clone() ... #region Member variables #region Attribute - price public Double Price { get { ... } set { ... } } #endregion #region Attribute - publicationdate public LiquidTechnologies.LtXmlLib4.XmlDateTime Publicationdate { get { ... } set { ... } } public Boolean IsValidPublicationdate { get { ... } set { ... } } protected Boolean m_IsValidPublicationdate; protected LiquidTechnologies.LtXmlLib4.XmlDateTime m_Publicationdate; #endregion #region Attribute - ISBN public String ISBN { get { ... } set { ... } } public Boolean IsValidISBN { get { ... } set { ... } } protected Boolean m_IsValidISBN; protected String m_ISBN; #endregion #region Attribute - title public String Title { get { ... } set { ... } } protected String m_Title; #endregion #region Attribute - author public BookStoreLib.AuthorName Author { get { ... } set { ... } } protected BookStoreLib.AuthorName m_Author; #endregion #region Attribute - genre public String Genre { get { ... } set { ... } } public Boolean IsValidGenre { get { ... } set { ... } } protected Boolean m_IsValidGenre; protected String m_Genre; #endregion #region Attribute - Namespace public override String Namespace { get { return "; } } #endregion #endregion // ##HAND_CODED_BLOCK_START ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS // Add Additional Methods and members here... // ##HAND_CODED_BLOCK_END ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS } }

BookTypeCol.cs

namespace BookStoreLib 
{
    public class BookTypeCol : LiquidTechnologies.LtXmlLib4.XmlCollectionBase
    {
        internal BookTypeCol(String elementName, String targetNamespace, int minOccurs, int maxOccurs)
        { ... }

        public BookStoreLib.BookType Add(BookStoreLib.BookType newCls)
        { ... }
        
        public BookStoreLib.BookType Add()
        { ... }

        public BookStoreLib.BookType this[int index] 
        { ... }
    
        public override object Clone()
        { ... }
        
        public override String Namespace            
        { 
            get { ...  }
        }
    }
}

AuthorName.cs

namespace BookStoreLib
{
    public class AuthorName  : LiquidTechnologies.LtXmlLib4.XmlGeneratedClass
    {
        public AuthorName()
... public AuthorName(String elementName) ... public override object Clone() ... #region Attribute - First_name public String First_name { get { ... } set { ... } } protected String m_First_name; #endregion #region Attribute - last-name public String Last_name { get { ... } set { ... } } protected String m_Last_name; #endregion // ##HAND_CODED_BLOCK_START ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS // Add Additional Methods and members here... // ##HAND_CODED_BLOCK_END ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS } }

Note

Unnecessary detail has been removed from the code above, in order to make it easier to understand, the download contains the full code.

 

Generated C++ Classes

Write Sample

Code

    try
    {
        // to create the XML document from scratch
        BookStoreLib::CBookstorePtr spBS = BookStoreLib::CBookstore::CreateInstance();
        BookStoreLib::CBookTypePtr spBook = spBS->GetBook()->Add();
        spBook->SetTitle(_T("The Autobiography of Benjamin Franklin"));
        spBook->SetPrice(8.99);
        spBook->SetPublicationdate(LtXmlLib4::CDateTime(1981, 5, 11));
        spBook->SetISBN(_T("1-861003-11-0"));
        spBook->GetAuthor()->SetFirst_name(_T("Benjamin"));
        spBook->GetAuthor()->SetLast_name(_T("Franklin"));
        spBook->SetGenre(_T("autobiography"));
        std::tstring strXml = spBook->ToXml();
        _tprintf(_T("This is the XML\n%s"), strXml.c_str());
    }
    catch (CLtException& e)
    {
        // Note : exceptions are likely to contain inner exceptions
        // that provide further detail about the error, GetFullMessage
        // concatantes the messages from them all.
        _tprintf(_T("Error - %s\n"), e.GetFullMessage().c_str());
    }

Output

Read Sample

Code

try
    {
        // to create the XML document from scratch
        BookStoreLib::CBookstorePtr spBS = BookStoreLib::CBookstore::CreateInstance();
        spBS->FromXmlFile(_T("BookStoreSample.xml"));

        for (BookStoreLib::CBookTypeCol::iterator itr = spBS->GetBook()->begin();
             itr != spBS->GetBook()->end();
             itr++)
        {
            BookStoreLib::CBookTypePtr spBook = *itr;

            _tprintf(_T("Book Title           %s\n"), spBook->GetTitle().c_str());
            _tprintf(_T("    Price            %f\n"), spBook->GetPrice());
            _tprintf(_T("    Author           %s %s\n"), 
                         spBook->GetAuthor()->GetFirst_name().c_str(), 
                         spBook->GetAuthor()->GetLast_name().c_str());
            if (spBook->IsValidPublicationdate())
                _tprintf(_T("    Publicationdate  %s\n"), spBook->GetPublicationdate()
                                                                      .ToString().c_str());
            else                    
                _tprintf(_T("    Publicationdate  Not Listed\n"));
            if (spBook->IsValidISBN())
                _tprintf(_T("    ISBN             %s\n"), spBook->GetISBN().c_str());
            else                    
                _tprintf(_T("    ISBN             Not Listed\n"));
            if (spBook->IsValidGenre())
                _tprintf(_T("    Genre            %s\n"), spBook->GetGenre().c_str());
            else                    
                _tprintf(_T("    Genre            Not Listed\n"));
        }
    }
    catch (CLtException& e)
    {
        // Note : exceptions are likely to contain inner exceptions
        // that provide further detail about the error, GetFullMessage
        // concatantes the messages from them all.
        _tprintf(_T("Error - %s\n"), e.GetFullMessage().c_str());
    }

Output

Generated Code

BookStore.h

#ifndef _BookStoreLib_BookStoreLib_CBookstore_h 
#define _BookStoreLib_BookStoreLib_CBookstore_h 

// Include Base classes
#include "../BookStoreLib/BookTypeCol.h" 
#include "../BookStoreLib/BookType.h" 

namespace BookStoreLib
{
    class BookStoreLib_DLL CBookstore : public CInstanceMonitor
                    , public virtual LtXmlLib4::CXmlGeneratedClass
    {
    public:
        static BookStoreLib::CBookstorePtr CreateInstance();

    public:
        BookStoreLib::CBookTypeColPtr GetBook();
    protected:
        BookStoreLib::CBookTypeColPtr m_Book;
            
    public:
        virtual std::tstring GetTargetNamespace() const;
        virtual std::tstring GetNamespace() const;
        virtual LtXmlLib4::CXmlObjectBase* GetBase();

// ##HAND_CODED_BLOCK_START ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS
// Add Additional Methods here...
// ##HAND_CODED_BLOCK_END ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS
    };
}; // end namespace (BookStoreLib)

#endif // _BookStoreLib_CBookstore_h 

BookType.h

#ifndef _BookStoreLib_BookStoreLib_CBookType_h 
#define _BookStoreLib_BookStoreLib_CBookType_h 

// Include Base classes
#include "../BookStoreLib/AuthorName.h" 

namespace BookStoreLib
{
    class BookStoreLib_DLL CBookType : public CInstanceMonitor
                    , public virtual LtXmlLib4::CXmlGeneratedClass
    {
    public:
        static BookStoreLib::CBookTypePtr CreateInstance();

    public:
        DOUBLE GetPrice();
        void SetPrice(DOUBLE val);
    protected:
        DOUBLE m_Price;

    public:
        LtXmlLib4::CDateTime GetPublicationdate();
        void SetPublicationdate(LtXmlLib4::CDateTime val);
    public:
        bool IsValidPublicationdate();
        void SetValidPublicationdate(bool val);
    protected:
        bool m_IsValidPublicationdate;
        LtXmlLib4::CDateTime m_Publicationdate;
    public:
        std::tstring GetISBN();
        void SetISBN(std::tstring val);
    public:
        bool IsValidISBN();
        void SetValidISBN(bool val);
    protected:
        bool m_IsValidISBN;
        std::tstring m_ISBN;
    public:
        std::tstring GetTitle();
        void SetTitle(std::tstring val);
    protected:
        std::tstring m_Title;

    public:
        BookStoreLib::CAuthorNamePtr GetAuthor();
        void SetAuthor(BookStoreLib::CAuthorName* value);
    protected:
        BookStoreLib::CAuthorNamePtr m_Author;
            
    public:
        std::tstring GetGenre();
        void SetGenre(std::tstring val);
    public:
        bool IsValidGenre();
        void SetValidGenre(bool val);
    protected:
        bool m_IsValidGenre;
        std::tstring m_Genre;
    
    public:
        virtual std::tstring GetTargetNamespace() const;
        virtual std::tstring GetNamespace() const;
        virtual LtXmlLib4::CXmlObjectBase* GetBase();

// ##HAND_CODED_BLOCK_START ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS
// Add Additional Methods here...
// ##HAND_CODED_BLOCK_END ID="Additional Methods"## DO NOT MODIFY ANYTHING OUTSIDE OF THESE TAGS
    };
}; // end namespace (BookStoreLib)

#endif // _BookStoreLib_CBookType_h 

BookTypeCol.h

#ifndef _BookStoreLib_BookStoreLib_CBookTypeCol_h 
#define _BookStoreLib_BookStoreLib_CBookTypeCol_h 

namespace BookStoreLib
{
    class BookStoreLib_DLL CBookTypeCol : public LtXmlLib4::CXmlCollectionBase, CInstanceMonitor
    {
    public:
        void Add      (BookStoreLib::CBookType* pCls);
        void AddAfter (BookStoreLib::CBookType* pClsPos, BookStoreLib::CBookType* pCls);
        void AddBefore(BookStoreLib::CBookType* pClsPos, BookStoreLib::CBookType* pCls);
        
        BookStoreLib::CBookTypePtr  Add();
    
        BookStoreLib::CBookTypePtr  Item(int index);
        void Remove(BookStoreLib::CBookType* pCls);

        typedef LtXmlLib4::CLtIterator<BookStoreLib::CBookType> iterator;

        iterator begin();
        iterator end();
    
        virtual std::tstring GetNamespace() const   { return _T("); }
    };
}; // end namespace (BookStoreLib)

#endif // _BookStoreLib_CBookTypeCol_h 

AuthorName.h

#ifndef _BookStoreLib_BookStoreLib_CAuthorName_h 
#define _BookStoreLib_BookStoreLib_CAuthorName_h 

namespace BookStoreLib
{
    class BookStoreLib_DLL CAuthorName : public CInstanceMonitor
                    , public virtual LtXmlLib4::CXmlGeneratedClass
    {
    public:
        static BookStoreLib::CAuthorNamePtr CreateInstance();

    public:
        std::tstring GetFirst_name();
        void SetFirst_name(std::tstring val);
    protected:
        std::tstring m_First_name;

    public:
        std::tstring GetLast_name();
        void SetLast_name(std::tstring val);
    protected:
        std::tstring m_Last_name;

    public:
        virtual std::tstring GetTargetNamespace() const;
        virtual std::tstring GetNamespace() const;
        virtual LtXmlLib4::CXmlObjectBase* GetBase();
    };
}; // end namespace (BookStoreLib)

#endif // _BookStoreLib_CAuthorName_h 

Note

Unnecessary detail has been removed from the code above, in order to make it easier to understand, the download contains the full code.

 

Generated Java Classes

Write Sample

Code

    try
    {
      // to create the XML document from scratch
      BookStoreLib.Bookstore bs = new BookStoreLib.Bookstore();
      BookStoreLib.BookType book = bs.getBook().add();
      book.setTitle("The Autobiography of Benjamin Franklin");
      book.setPrice(8.99);
      book.setPublicationdate(
         new com.liquid_technologies.ltxmllib4.DateTime((short)1981, (byte)5, (byte)11));
      book.setISBN("1-861003-11-0");
      book.getAuthor().setFirst_name("Benjamin");
      book.getAuthor().setLast_name("Franklin");
      book.setGenre("autobiography");
      String strXml = book.toXml();
      System.out.println("This is the XML\n" + strXml);
    }
    catch (Exception e)
    {
      // Note : exceptions are likely to contain inner exceptions
      // that provide further detail about the error.
      Throwable te = e;
      while (te != null)
      {
        System.out.println("Error - " + te.getMessage());
        te = te.getCause();
      }
    }

Output

Read Sample

Code

    try
    {
      // to create the XML document from scratch
      BookStoreLib.Bookstore bs = new BookStoreLib.Bookstore();
      bs.fromXmlFile("BookStoreSample.xml");

      for (int i=0; i<bs.getBook().count(); i++)
      {
        BookStoreLib.BookType book = bs.getBook().getItem(i);

        System.out.println("Book Title           " + book.getTitle());
        System.out.println("    Price            " + book.getPrice());
        System.out.println("    Author           " + book.getAuthor().getFirst_name() 
                                                    + " " + book.getAuthor().getLast_name());
        if (book.isValidPublicationdate())
          System.out.println("    Publicationdate  " + book.getPublicationdate().toString());
        else                    
          System.out.println("    Publicationdate  Not Listed");
        if (book.isValidISBN())
          System.out.println("    ISBN             " + book.getISBN());
        else                    
          System.out.println("    ISBN             Not Listed");
        if (book.isValidGenre())
          System.out.println("    Genre            " + book.getGenre());
        else                    
          System.out.println("    Genre            Not Listed");
      }
    }
    catch (Exception e)
    {
      // Note : exceptions are likely to contain inner exceptions
      // that provide further detail about the error.
      Throwable te = e;
      while (te != null)
      {
        System.out.println("Error - " + te.getMessage());
        te = te.getCause();
      }
    }

Output

Generated Code

BookStore.java

package BookStoreLib;
 
import java.io.IOException;

public class Bookstore  extends com.liquid_technologies.ltxmllib4.XmlGeneratedClass
{
  public Bookstore()
  { .. }
  public Bookstore(String elementName)
  { .. }

  public Object clone() 
    throws CloneNotSupportedException
  { .. }

  public String getTargetNamespace()
  { .. }

  public BookStoreLib.BookTypeCol getBook()
  { .. }

  public String getNamespace()
  { .. }

  public com.liquid_technologies.ltxmllib4.XmlObjectBase getBase()
  { .. }
}

BookType.java

package BookStoreLib;
 
import java.io.IOException;

public class Bookstore  extends com.liquid_technologies.ltxmllib4.XmlGeneratedClass
{
  public Bookstore()
  { .. }
  public Bookstore(String elementName)
  { .. }

  public Object clone() 
    throws CloneNotSupportedException
  { .. }

  public String getTargetNamespace()
  { .. }
  public double getPrice() 
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }
public void setPrice(double value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected double _price; public com.liquid_technologies.ltxmllib4.DateTime getPublicationdate() throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public void setPublicationdate(com.liquid_technologies.ltxmllib4.DateTime value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public boolean isValidPublicationdate() { .. } public void setValidPublicationdate(boolean value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected boolean _isValidPublicationdate; protected com.liquid_technologies.ltxmllib4.DateTime _publicationdate; public java.lang.String getISBN() throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public void setISBN(java.lang.String value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public boolean isValidISBN() { .. } public void setValidISBN(boolean value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected boolean _isValidISBN; public java.lang.String getTitle() throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public void setTitle(java.lang.String value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected java.lang.String _title; public BookStoreLib.AuthorName getAuthor() { .. } public void setAuthor(BookStoreLib.AuthorName value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected BookStoreLib.AuthorName _author; public java.lang.String getGenre() throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public void setGenre(java.lang.String value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } public boolean isValidGenre() { .. } public void setValidGenre(boolean value) throws com.liquid_technologies.ltxmllib4.exceptions.LtException { .. } protected boolean _isValidGenre; protected java.lang.String _genre; public String getNamespace() { .. } public com.liquid_technologies.ltxmllib4.XmlObjectBase getBase() { .. } }

BookTypeCol.java

package BookStoreLib;

import java.util.Iterator;
import java.io.IOException;

public class BookTypeCol extends com.liquid_technologies.ltxmllib4.XmlCollectionBase
{
  public BookTypeCol(String elementName, String targetNamespace, int minOccurs, int maxOccurs)
  { .. }

  public BookStoreLib.BookType  add(BookStoreLib.BookType newCls)
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }

  public BookStoreLib.BookType add()
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }

  public BookStoreLib.BookType getItem(int index)
  { .. }

  public Object clone() throws CloneNotSupportedException
  { .. }

  public String getTargetNamespace()
  { .. }

  public String getNamespace()
  { .. }
}

AuthorName.java

package BookStoreLib;
 
import java.io.IOException;

public class Bookstore  extends com.liquid_technologies.ltxmllib4.XmlGeneratedClass
{
  public Bookstore()
  { .. }
  public Bookstore(String elementName)
  { .. }

  public Object clone() throws CloneNotSupportedException
  { .. }

  public String getTargetNamespace()
  { .. }

  public java.lang.String getFirst_name() 
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }
  public void setFirst_name(java.lang.String value)
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }
  protected java.lang.String  _first_name;

  public java.lang.String getLast_name() 
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }
  public void setLast_name(java.lang.String value) 
    throws com.liquid_technologies.ltxmllib4.exceptions.LtException
  { .. }
  protected java.lang.String  _last_name;

  public String getNamespace()
  { .. }

  public com.liquid_technologies.ltxmllib4.XmlObjectBase getBase()
  { .. }
}

Note

Unnecessary detail has been removed from the code above, in order to make it easier to understand, the download contains the full code.

 

Generated Visual Basic Classes

Write Sample

Code

    Dim oBS As BookStoreLib.Bookstore
    Dim oBook As BookStoreLib.BookType
    Dim oDt As LtXmlComLib4.DateTime
    Dim strXml As String
    
    ' to create the XML document from scratch
    Set oBS = New BookStoreLib.Bookstore
    Set oBook = oBS.Book.AddNew
    
    oBook.Title = "The Autobiography of Benjamin Franklin"
    oBook.Price = 8.99
    Set oDt = New LtXmlComLib4.DateTime
    oDt.SetDate 1981, 5, 11
    Set oBook.Publicationdate = oDt
    oBook.ISBN = "1-861003-11-0"
    oBook.Author.First_name = "Benjamin"
    oBook.Author.Last_name = "Franklin"
    oBook.Genre = "autobiography"
    strXml = oBS.ToXml
    Debug.Print strXml

 

Output

Read Sample

Code

    Dim oBS As BookStoreLib.Bookstore
    Dim oBook As BookStoreLib.BookType
    
    ' to create the XML document from scratch
    Set oBS = New BookStoreLib.Bookstore
    oBS.FromXmlFile "C:\Development4\Liquid\Documentation\DemoApp\BookStoreDemo\BookStoreSample.xml"
    
    For Each oBook In oBS.Book
        Debug.Print "Book Title           " & oBook.Title
        Debug.Print "    Price            " & oBook.Price
        Debug.Print "    Author           " & oBook.Author.First_name & " " & oBook.Author.Last_name
        If oBook.IsValidPublicationdate Then
            Debug.Print "    Publicationdate  " & oBook.Publicationdate.ToString("s")
        Else
            Debug.Print "    Publicationdate  Not Listed"
        End If
        If oBook.IsValidISBN Then
            Debug.Print "    ISBN             " & oBook.ISBN
        Else
            Debug.Print "    ISBN             Not Listed"
        End If
        If oBook.IsValidGenre Then
            Debug.Print "    Genre            " & oBook.Genre
        Else
            Debug.Print "    Genre            Not Listed"
        End If
    Next oBook

Output

Generated Code

BookStore.cls

Option Explicit
private m_ElementName as String
private WithEvents mvarBook as BookStoreLib.BookTypeCol 



Implements LtXmlComLib4.XmlObjectBase
Implements LtXmlComLib4.XmlGeneratedClass



Public Property Get ElementName() As String
    ElementName = m_elementName
End Property


Public Property Get Book as BookStoreLib.BookTypeCol 
    Set Book = mvarBook
End Property



''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''' Standard Methods '''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Sub ToXmlFile(ByVal FileName As String, _
         Optional includeDocHeader As Boolean = True, _
         Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
         Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
         Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_CRLF, _
         Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Function ToXml(Optional includeDocHeader As Boolean = True, _
         Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
         Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
         Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As String
    ...
End Function
Public Function ToXmlStream(Optional includeDocHeader As Boolean = True, _
         Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
         Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
         Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
         Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As Variant
    ...
End Function
Public Sub FromXml(ByVal xmlIn As String, _ 
         Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Sub FromXmlFile(ByVal FileName As String, _
          Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub

BookType.cls

Option Explicit

Private m_elementName As String
Private mvarPrice As Double
Private mvarIsValidPublicationdate As Boolean
Private mvarPublicationdate As LtXmlComLib4.DateTime
Private mvarIsValidISBN As Boolean
Private mvarISBN As String
Private mvarTitle As String
Private mvarAuthor As BookStoreLib.AuthorName
Private mvarIsValidGenre As Boolean
Private mvarGenre As String



Implements LtXmlComLib4.XmlObjectBase
Implements LtXmlComLib4.XmlGeneratedClass


Public Property Get ElementName() As String
    ElementName = m_elementName
End Property


Public Property Get Price() As Double
    ...
End Property

Public Property Let Price(ByVal value As Double)
    ...
End Property


Public Property Get Publicationdate() As LtXmlComLib4.DateTime
    ...
End Property

Public Property Set Publicationdate(ByVal value As LtXmlComLib4.DateTime)
    ...
End Property


Public Property Get IsValidPublicationdate() As Boolean
    ...
End Property
Public Property Let IsValidPublicationdate(ByVal value As Boolean)
    ...
End Property


Public Property Get ISBN() As String
    ...
End Property

Public Property Let ISBN(ByVal value As String)
    ...
End Property



Public Property Get IsValidISBN() As Boolean
    ...
End Property
Public Property Let IsValidISBN(ByVal value As Boolean)
    ...
End Property


Public Property Get Title() As String
    ...
End Property

Public Property Let Title(ByVal value As String)
    ...
End Property


Public Property Get Author() As BookStoreLib.AuthorName
    ...
End Property
Public Property Set Author(ByVal value As BookStoreLib.AuthorName)
    ...
End Property
        

Public Property Get Genre() As String
    ...
End Property

Public Property Let Genre(ByVal value As String)
    ...
End Property

Public Property Get IsValidGenre() As Boolean
    ...
End Property
Public Property Let IsValidGenre(ByVal value As Boolean)
    ...
End Property

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''' Standard Methods '''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Sub ToXmlFile(ByVal FileName As String, _
             Optional includeDocHeader As Boolean = True, _
             Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
             Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
             Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_CRLF, _
             Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Function ToXml(Optional includeDocHeader As Boolean = True, _
             Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
             Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
             Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As String
    ...
End Function
Public Function ToXmlStream(Optional includeDocHeader As Boolean = True, _
             Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
             Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
             Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
             Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As Variant
    ...
End Function
Public Sub FromXml(ByVal xmlIn As String, _
             Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Sub FromXmlFile(ByVal FileName As String, _
             Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub

BookTypeCol.cls

Option Explicit
private m_elementName   as string
private m_minOccurs     as long
private m_maxOccurs     as long
private m_coll          as Collection

Public Event OnCollectionChange()

Implements LtXmlComLib4.XmlCollectionBase
Implements LtXmlComLib4.XmlObjectBase

public Function Add(ByVal newCls as BookStoreLib.BookType) as BookStoreLib.BookType 
    ...
End Function 
        
public Function AddNew() as BookStoreLib.BookType 
    ...
End Function

public property Get Item(byval index as long) as BookStoreLib.BookType 
    ...
End Property

Public Property Get Count() As Long
    ...
End Property

Public Sub Remove(ByVal index As Long)
    ...
End Sub

Public Sub Clear()
    ...
End Sub

Public Property Get NewEnum() As IUnknown
    ...
End Property

AuthorName.cls

Option Explicit
private m_ElementName as String
private mvarFirst_name as String 
private mvarLast_name as String 



Implements LtXmlComLib4.XmlObjectBase
Implements LtXmlComLib4.XmlGeneratedClass



Public Property Get ElementName() As String
    ...
End Property


Public Property Get First_name as String 
    ...
End Property

Public Property Let First_name(byval value as String)
    ...
End Property


Public Property Get Last_name as String 
    ...
End Property

Public Property Let Last_name(byval value as String)
    ...
End Property
 
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''' Standard Methods '''''''''''''''''''''''''''''''''''''''''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

Public Sub ToXmlFile(ByVal FileName As String, _
            Optional includeDocHeader As Boolean = True, _
            Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
            Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
            Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_CRLF, _
            Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Function ToXml(Optional includeDocHeader As Boolean = True, _
            Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
            Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
            Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As String
    ...
End Function
Public Function ToXmlStream(Optional includeDocHeader As Boolean = True, _
            Optional formatting As LtXmlComLib4.XmlFormatting = LtXmlComLib4.XmlFormatting_Indented, _
            Optional encoding As LtXmlComLib4.XmlEncoding = LtXmlComLib4.XmlEncoding_UTF8, _
            Optional EOL As LtXmlComLib4.EOLType = LtXmlComLib4.EOLType.EOLType_LF, _
            Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) As Variant
    ...
End Function
Public Sub FromXml(ByVal xmlIn As String, _
            Optional context As LtXmlComLib4.XmlSerializationContext = Nothing)
    ...
End Sub
Public Sub FromXmlFile(ByVal FileName As String, _
Optional context As LtXmlComLib4.XmlSerializationContext = Nothing) ... End Sub

Note

Unnecessary detail has been removed from the code above, in order to make it easier to understand, the download contains the full code.

 

The Viewer Displaying the Sample

If you download the source, included in the zip is an object viewer. This viewer is a graphical representation of the classes/objects contained within the library. You can use the viewer to change the values of properties within the class library, it will even provide the code necessary to re-construct the XML that is currently loaded into the library. This is a useful way to familiarize yourself with the structure of a generated library

The Sample XSD, Sample XML, Generated code and object viewer, can be downloaded here
(The viewer requires the .Net framework to be installed)