login | register    

XML Data Binding for .Net C# (CSharp)

Reasons to Use XML Data Binding

 
  • Reduces Development Time
  • Increased reliability (spot problems at compile time not runtime)
  • Creates more readable code
  • Fastest root between code and XML

Reasons To Use Liquid XML Data Binding Code Generator

   
  • Generates simple intuitive code
  • Supports XSD, XDR & DTD's
  • Unrivaled W3C XSD standard support, handles with the most complex XML standards where xsd.exe would fail.
  • .Net Data Binding support


Xml Data Binding

XML Data Binding allows you to treat your XML documents as objects within your application. This makes dealing with XML data from a programming language a simple matter of manipulating these strongly typed objects.

Liquid XML Data Binding Code Generator takes an XML Schema and uses it to generate a class library. These classes map directly to to data contained in your XML Schema, so if your schema has an Person entity and that has a date of birth attribute, then a class called Person will be generated, which will have a property called DateOfBirth.

 

Strongly Typed Code

Liquid XML Data Binder creates simple intuitive code from your XML Schema. The code library contains strongly typed classes and collections.

Customisable Code

The generated output may also be modified within special 'Hand Coded Blocks', changes inside these blocks are persisted when the library is re-generated, allowing the library to be customised to fit the projects needs.

 

Tools Included with Liquid XML Studio

Liquid XML Data Binding Code Generator is included in the Developer Edition of Liquid XML Studio, which includes many other XML tools including
XSD Editor, XML Editor, XML Differencing tool, XPath Query viewer, Web Service Call Composer and more... see Liquid XML Studio.

Standard Support

The use of XML is exploding, and with it the number and complexity of 3rd party standards. There are now 1000's of XML Schemas describing everything from Solar orbits to coffee bean quality. Because the XSD standard is complex, many XML Data Binding tools only support a sub set of it. This may be adequate for small in house schemas, but in the real world you need something that will cope with the standards that exist out in the wild. Liquid XML Data Binder has an unprecedented level of support for the W3C XSD Standard allowing it to cope with the most complex standards, just try it and see.

 

A Simple Example

The following example we will use the Person.xsd, shown below to demonstrate how to read and write an XML document based on this schema.

XML Schema - Bookstore.xsd - Click to View
The model for Bookstore.xsd
The Bookstore.xsd schema shown graphically using Liquid XML Studio
1<?xml version="1.0" encoding="utf-16"?> 2<!--Created with Liquid XML Studio --> 3<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> 4 <xs:element name="Person"> 5 <xs:complexType> 6 <xs:sequence> 7 <xs:element name="Name" type="xs:string" /> 8 <xs:element name="DateOfBirth" type="xs:date" /> 9 <xs:element minOccurs="0" name="Address"> 10 <xs:complexType> 11 <xs:sequence> 12 <xs:element name="HouseNo" type="xs:int" /> 13 <xs:element name="PostCode" type="xs:string" /> 14 </xs:sequence> 15 </xs:complexType> 16 </xs:element> 17 <xs:element minOccurs="0" maxOccurs="unbounded" name="Car"> 18 <xs:complexType> 19 <xs:sequence> 20 <xs:element name="Make" type="xs:string" /> 21 <xs:element name="Model" type="xs:string" /> 22 </xs:sequence> 23 </xs:complexType> 24 </xs:element> 25 </xs:sequence> 26 </xs:complexType> 27 </xs:element> 28</xs:schema>


Sample XML File - BookStoreSample.xml - Click to View
1<?xml version="1.0"?> 2<Person> 3 <Name>Fred</Name> 4 <DateOfBirth>1978-06-26</DateOfBirth> 5 <Address> 6 <HouseNo>7</HouseNo> 7 <PostCode>WV6 6JY</PostCode> 8 </Address> 9 <Car> 10 <Make>Escort</Make> 11 <Model>Ford</Model> 12 </Car> 13 <Car> 14 <Make>Elise</Make> 15 <Model>Lotus</Model> 16 </Car> 17</Person> 18

Serializing the XML (Objects to XML) - Code to create an XML document using XML Data Binding Objects - Click to View

Using XML Data Binding

Using the standard DOM approach

1Person p = new Person(); 2p.Name = "Fred"; 3p.DateOfBirth = new XmlDateTime(1978, 6, 26); 4 5Address a = new Address(); 6p.Address = a; 7p.Address.HouseNo = 7; 8p.Address.PostCode = "WV6 6JY"; 9 10Car runAroundCar = new Car(); 11p.Cars.Add(runAroundCar); 12runAroundCar.Model = "Ford"; 13runAroundCar.Make = "Escort"; 14 15Car toyCar = new Car(); 16p.Cars.Add(toyCar); 17toyCar.Model = "Lotus"; 18toyCar.Make = "Elise"; 19 20Debug.WriteLine(p.ToXml()); 21 22p.ToXmlFile("SampleFile.xml");
1XmlDocument xmlDoc = new XmlDocument(); 2XmlElement xmlElmPerson = xmlDoc.CreateElement("Person"); 3xmlDoc.AppendChild(xmlElmPerson); 4 5XmlElement xmlElmName = xmlDoc.CreateElement("Name"); 6xmlElmPerson.AppendChild(xmlElmName); 7xmlElmName.InnerText = "Fred"; 8 9XmlElement xmlElmDOB = xmlDoc.CreateElement("DateOfBirth"); 10xmlElmPerson.AppendChild(xmlElmDOB); 11xmlElmDOB.InnerText = "1978-06-26"; 12 13XmlElement xmlElmAddress = xmlDoc.CreateElement("Address"); 14xmlElmPerson.AppendChild(xmlElmAddress); 15 16XmlElement xmlElmHouseNo = xmlDoc.CreateElement("HouseNo"); 17xmlElmAddress.AppendChild(xmlElmHouseNo); 18xmlElmHouseNo.InnerText = "7"; 19 20XmlElement xmlElmPostCode = xmlDoc.CreateElement("PostCode"); 21xmlElmAddress.AppendChild(xmlElmPostCode); 22xmlElmPostCode.InnerText = "WV6 6JY"; 23 24XmlElement xmlElmCarRA = xmlDoc.CreateElement("Car"); 25xmlElmPerson.AppendChild(xmlElmCarRA); 26 27XmlElement xmlElmRAModel = xmlDoc.CreateElement("Model"); 28xmlElmCarRA.AppendChild(xmlElmRAModel); 29xmlElmRAModel.InnerText = "Ford"; 30 31XmlElement xmlElmRAMake = xmlDoc.CreateElement("Make"); 32xmlElmCarRA.AppendChild(xmlElmRAMake); 33xmlElmRAMake.InnerText = "Escort"; 34 35XmlElement xmlElmCarToy = xmlDoc.CreateElement("Car"); 36xmlElmPerson.AppendChild(xmlElmCarToy); 37 38XmlElement xmlElmToyModel = xmlDoc.CreateElement("Model"); 39xmlElmCarToy.AppendChild(xmlElmToyModel); 40xmlElmToyModel.InnerText = "Lotus"; 41 42XmlElement xmlElmToyMake = xmlDoc.CreateElement("Make"); 43xmlElmCarToy.AppendChild(xmlElmToyMake); 44xmlElmToyMake.InnerText = "Elise"; 45 46using (StringWriter sr = new StringWriter()) 47{ 48 XmlWriterSettings xws = new XmlWriterSettings(); 49 xws.Indent = true; 50 51 using (XmlWriter xtw = XmlTextWriter.Create(sr, xws)) 52 { 53 xmlDoc.WriteTo(xtw); 54 } 55 Debug.WriteLine(sr.ToString()); 56}
The XML Data Binding code is much easier to read, more concise and will allow errors to be detected at compile time should the data model change.
The DOM code is verbose, difficult to read, and should the data model change, the errors will only be picked up in testing.

Deserializing the XML (XML to Objects) - Code to read an XML document using XML Data Binding Objects - Click to View

Using XML Data Binding

Using the standard DOM approach

1p.FromXmlFile("SampleFile.xml"); 2 3Debug.WriteLine( 4 String.Format( 5 "{0} was born {1}, and lives at {2}, {3}", 6 p.Name, 7 p.DateOfBirth.ToString(), 8 p.Address.HouseNo, 9 p.Address.PostCode)); 10 11Debug.WriteLine( 12 String.Format( 13 "Cars Owned ({0})", p.Cars.Count)); 14foreach (Car c in p.Cars) 15{ 16 Debug.WriteLine( 17 string.Format(" {0}, {1}", 18 c.Make, 19 c.Model)); 20}
1XmlDocument xmlDoc = new XmlDocument(); 2xmlDoc.Load("SampleFile.xml"); 3 4XmlElement xmlElmPerson = GetFirstElement(xmlDoc); 5if (xmlElmPerson == null || xmlElmPerson.Name != "Person") 6 throw new Exception("Must start with Person"); 7 8XmlElement xmlElmName = GetFirstElement(xmlElmPerson); 9if (xmlElmName == null || xmlElmName.Name != "Name") 10 throw new Exception("Missing Person->Name"); 11 12XmlElement xmlElmDOB = GetNextElement(xmlElmName); 13if (xmlElmDOB == null || xmlElmDOB.Name != "DateOfBirth") 14 throw new Exception("Missing Person->DateOfBirth"); 15 16XmlElement xmlElmAddress = GetNextElement(xmlElmDOB); 17if (xmlElmAddress == null || xmlElmAddress.Name != "Address") 18 throw new Exception("Missing Person->Address"); 19 20 21XmlElement xmlElmHouseNo = GetFirstElement(xmlElmAddress); 22if (xmlElmHouseNo == null || xmlElmHouseNo.Name != "HouseNo") 23 throw new Exception("Missing Person->Address->HouseNo"); 24 25XmlElement xmlElmPostCode = GetNextElement(xmlElmHouseNo); 26if (xmlElmPostCode == null || xmlElmPostCode.Name != "PostCode") 27 throw new Exception("Missing Person->Address->PostCode"); 28 29if (GetNextElement(xmlElmPostCode) != null) 30 throw new Exception("Unexpected Element found"); 31 32Debug.WriteLine( 33 String.Format( 34 "{0} was born {1}, and lives at {2}, {3}", 35 xmlElmName.InnerText, 36 xmlElmDOB.InnerText, 37 xmlElmHouseNo.InnerText, 38 xmlElmPostCode.InnerText)); 39 40XmlElement xmlElmCar = GetNextElement(xmlElmAddress); 41while (xmlElmCar != null) 42{ 43 if (xmlElmCar.Name != "Car") 44 throw new Exception("Unknown element " + xmlElmCar.Name); 45 46 XmlElement xmlElmMake = GetFirstElement(xmlElmCar); 47 if (xmlElmMake == null || xmlElmMake.Name != "Make") 48 throw new Exception("Missing Person->Car->Make"); 49 50 XmlElement xmlElmModel = GetNextElement(xmlElmMake); 51 if (xmlElmModel == null || xmlElmModel.Name != "Model") 52 throw new Exception("Missing Person->Car->Model"); 53 54 if (GetNextElement(xmlElmModel) != null) 55 throw new Exception("Unexpected Element found"); 56 57 Debug.WriteLine( 58 string.Format(" {0}, {1}", 59 xmlElmMake.InnerText, 60 xmlElmModel.InnerText)); 61 62 xmlElmCar = GetNextElement(xmlElmCar); 63}
1private static XmlElement GetFirstElement(XmlNode xmlParent) 2{ 3 if (xmlParent == null) 4 return null; 5 else if (xmlParent.FirstChild == null) 6 return null; 7 else if (xmlParent.FirstChild is XmlElement) 8 return xmlParent.FirstChild as XmlElement; 9 else 10 return GetNextElement(xmlParent.FirstChild); 11} 12 13private static XmlElement GetNextElement(XmlNode xmlNode) 14{ 15 while (xmlNode != null) 16 { 17 xmlNode = xmlNode.NextSibling; 18 if (xmlNode is XmlElement) 19 return xmlNode as XmlElement; 20 } 21 return null; 22}
Because the XML Data Binding code does the bulk of the parsing fo you, manipulating the XML objects is just a matter of dealing with collections of objects, no need to continually check the type of an item etc.

Conclusion

XML Data Binding makes it significantly easier to deal with XML documents from within your code, resulting in less code, which is simpler to read and maintain.

As the generated class library is strongly typed, it forms a kind of template for the developer, ensuring that the data created conforms the underlying XML Schema.

The maintenance phase of a project also befits as XML Data Binding allows any errors introduced because of changes in the data model to be caught early at compile time, unlike weekly typed DOM trees, which will give no indication of a problem until runtime. These kinds of changes can be a major cause of bugs which can only be caught in testing. Being able to identify these at compile time can save huge amounts of time and effort.