Click here to Skip to main content
Click here to Skip to main content

Convert XML data to object and back using serialization

By , 18 May 2005
 

Introduction

Saving XML to a class object gives greater flexibility and maintainability. Moreover, it’s the preferred way of returning data from web services as compared to using DataSets. Saving XML to a class object is called serialization and reading back using the reverse process is named as deserialization.

Process\sample

Let's take an example of an XSD named Emp.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="Emp">
  <xs:complexType>
   <xs:sequence>
    <xs:element name="EmpInfo" type="EmpInfo"/>
   </xs:sequence>
  </xs:complexType>
 </xs:element>
 <xs:complexType name="EmpInfo">
  <xs:sequence>
   <xs:element name="Code" type="requiredString"/>
   <xs:element name="FirstName" type="requiredString"/>
   <xs:element name="LastName" type="requiredString"/>
   <xs:element name="Destination" type="requiredString"/>
  </xs:sequence>
 </xs:complexType>
 <xs:simpleType name="requiredString">
  <xs:annotation>
   <xs:documentation>template for required strings</xs:documentation>
  </xs:annotation>
  <xs:restriction base="xs:string">
   <xs:minLength value="1"/>
  </xs:restriction>
 </xs:simpleType>
 <xs:simpleType name="optionalString">
  <xs:annotation>
   <xs:documentation>template for optional strings</xs:documentation>
  </xs:annotation>
  <xs:restriction base="xs:string">
   <xs:minLength value="0"/>
  </xs:restriction>
 </xs:simpleType>
</xs:schema>

Now, to convert a class from XSD, we would run the following command:

xsd C:\Emp.xsd /t:lib /l:cs /c

from the Visual Studio .NET 2003 command prompt. This would create a class file named Emp.

EMP Class

//------------------------------------------------------------------------------
// <autogenerated>
//     This code was generated by a tool.
//     Runtime Version: 1.1.4322.2032

//
//     Changes to this file may cause incorrect behavior and will be lost if 
//     the code is regenerated.
// </autogenerated>
//------------------------------------------------------------------------------
// 
// This source code was auto-generated by xsd, Version=1.1.4322.2032.
// 
using System.Xml.Serialization;
/// <remarks/>
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public class Emp {
    
    /// <remarks/>
    public EmpInfo EmpInfo;
}

/// <remarks/>
public class EmpInfo {
    
    /// <remarks/>
    public string Code;
    
    /// <remarks/>
    public string FirstName;
    
    /// <remarks/>
    public string LastName;
    
    /// <remarks/>
    public string Destination;
}

Now, we could save an employee XML data to this class using the function:

  /// <summary>
  /// Returns an emp xsd class object based on the xml data passed
  /// </summary>
  /// <param name="xml">xml data of employee</param>
  /// <returns></returns>
  public Emp EmpObject(string xml)
  {
   StringReader stream = null;
   XmlTextReader reader = null;
   try
   {
    // serialise to object
    XmlSerializer serializer = new XmlSerializer(typeof(Emp));
    stream = new StringReader(xml); // read xml data
    reader = new XmlTextReader(stream);  // create reader
    // covert reader to object
    return (Emp)serializer.Deserialize(reader);
   }
   catch
   {
    return null;
   }
   finally
   {
    if(stream != null) stream.Close();
    if(reader != null) reader.Close();
   }
  }

And to get the XML based on the Emp class object, use the following function:

  /// <summary>
  /// Returns the xml as string based on emp object values
  /// </summary>
  /// <param name="emp">object that would be converted into xml</param>
  /// <returns></returns>
  public string EmpXml(Emp emp)
  {
   MemoryStream stream = null;
   TextWriter writer = null;
   try
   {
    stream = new MemoryStream(); // read xml in memory
    writer = new StreamWriter(stream, Encoding.Unicode) ;
    // get serialise object
    XmlSerializer serializer = new XmlSerializer(typeof(Emp));
    serializer.Serialize(writer, emp); // read object
    int count = (int) stream.Length; // saves object in memory stream
    byte[] arr = new byte[count];
    stream.Seek(0, SeekOrigin.Begin);
    // copy stream contents in byte array
    stream.Read(arr, 0, count);
    UnicodeEncoding utf = new UnicodeEncoding(); // convert byte array to string
    return utf.GetString(arr).Trim();
   }
   catch
   {
    return string.Empty;
   }
   finally
   {
    if(stream != null) stream.Close();
    if(writer != null) writer.Close();
   }
  }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

S Sansanwal
Architect
Australia Australia
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionThank you came in handymembersailakfan19 Jul '11 - 7:59 
GeneralMy vote of 2memberHoward Richards20 Sep '09 - 21:18 
GeneraltanxmemberNone_Force26 May '09 - 0:53 
GeneralTrouble using the xsd command with SVG schemamemberAmitDey30 Jul '08 - 21:02 
Questionxsd C:\Emp.xsd /t:lib /l:cs /c [modified]memberMyronJames18 Jul '07 - 5:26 
Hi,
 
   I FIGURED IT OUT!  
 
   I needed to add this line of code: <xs:element name="DistOrdrForm" type="DistOrderForm" />
 
   Above this line of code: <xs:complexType name="DistOrderForm">
 
   Why VS2005 didn't do that is a mystery, but I found the fix here:
   http://samples.gotdotnet.com/quickstart/howto/doc/xmlserialization/XSDToCls.aspx
 

   I attmpted to run this command, but I get this error 'Warning: cannot generate classes because no top-level elements with complex type were found.'   Now, I created the .xsd file from the graphical interface in VS2005.   BTW I'm using VB.NET.   Would that change the command string? I did change it to: xsd XSDtemplate.xsd /t:lib /l:vb /c         Is that correct??
 

Here's some of the code:
 

<!--<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XSDtemplate" targetNamespace="http://tempuri.org/XSDtemplate.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XSDtemplate.xsd" xmlns:mstns="http://tempuri.org/XSDtemplate.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema">
   <xs:complexType name="DistOrderForm">
      <xs:sequence>
         <xs:element name="PG1" type="Page1" />
         <xs:element name="PG2" type="Page2" />
         <xs:element name="PG3" type="Page3" />
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="Page1">
      <xs:sequence>
         <xs:element name="DistRefNo" type="xs:string" />
         <xs:element name="DistContact" type="xs:string" />
         <xs:element name="EndUser" type="xs:string" />
         <xs:element name="JobLocation" type="xs:string" />
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="Order">
      <xs:sequence>
         <xs:element name="OrderNo" type="xs:string" />
         <xs:element name="Supplement" type="xs:string" />
         <xs:element name="Date" type="xs:date" />
         <xs:element name="Rev" type="xs:string" />
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="Page2">
      <xs:sequence>
         <xs:element name="Order_info" type="Order" />
         <xs:element name="VIP_Frame" type="VIP_Frame_Options" />
         <xs:element name="VIP_Cylinder" type="VIP_CYL_Options" />
         <xs:element name="Other" type="Other" />
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="VIP_Frame_Options">
      <xs:sequence>
         <xs:element name="DeductFrameOilCooler" type="DeductFrameOilCooler" />
         <xs:element name="DeductCylLubeSys" type="DeductCylLubeSys" />
         <xs:element name="AddExplosionReliefDev" type="AddExplosionReliefDev" />
         <xs:element name="AddCrankcaseHeater" type="AddCrankcaseHeater" />
         <xs:element name="AddTEMA_C" type="AddTEMA_C" />
         <xs:element name="AddP2PLube" type="AddP2PLube" />
         <xs:element name="AddHeater4CylLube" type="AddHeater4CylLube" />
         <xs:element name="AddTorsional" type="AddTorsional" />
         <xs:element name="AddFlywheel" type="AddFlywheel" />
         <xs:element name="AddSingleCompartment" type="AddSingleCompartment" />
         <xs:element name="Add2Compartment" type="Add2Compartment" />
         <xs:element name="PurgedCylRodPacking" type="PurgedCylRodPacking" />
         <xs:element name="PurgedFramEndScraperRings" type="PurgedFramEndScraperRings" />
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name="Page3">
      <xs:sequence>
         <xs:element name="Order_info" type="Order" />
         <xs:element name="VIP_Frame" type="VIP_Frame_Options" />
         <xs:element name="VIP_Cylinder" type="VIP_CYL_Options" />
         <xs:element name="Other" type="Other" />
      </xs:sequence>-->
Please Help!!!
 
This is driving me nuts!!
 

 
Myron James
 

 
-- modified at 13:08 Wednesday 18th July, 2007
Generalnoice aRtickle !@!memberkoms1613 Feb '07 - 22:10 
GeneralStill More Genericmemberasithangae24 May '06 - 0:06 
GeneralRe: Still More Generic (sample using Generics for .net 2.0 or later)membercontato.atsa31 Mar '08 - 2:23 
GeneralSaved my daysussskjagini6 Sep '05 - 2:19 
GeneralCodeXS XSD-to-Code Generator ToolmemberWillem Fourie25 May '05 - 23:49 
GeneralVery cool!!memberSteven Bristol19 May '05 - 2:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 18 May 2005
Article Copyright 2005 by S Sansanwal
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid