Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / XML
Article

Convert XML data to object and back using serialization

Rate me:
Please Sign up or sign in to vote.
2.80/5 (23 votes)
18 May 2005 209K   40   12
This article describes the process of converting an XSD to a class and then reading and writing XML to\from the class object.

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

C#
//------------------------------------------------------------------------------
// <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>
//------------------------------------------------------------------------------
C#
// 
// This source code was auto-generated by xsd, Version=1.1.4322.2032.
// 
using System.Xml.Serialization;
C#
/// <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:

C#
  /// <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:

C#
  /// <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


Written By
Architect
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionI didnt get any automated code while running my Command promt Pin
Member 1284022915-Nov-16 2:43
Member 1284022915-Nov-16 2:43 
QuestionThank you came in handy Pin
sailakfan19-Jul-11 7:59
sailakfan19-Jul-11 7:59 
GeneralMy vote of 2 Pin
Howard Richards20-Sep-09 21:18
Howard Richards20-Sep-09 21:18 
Generaltanx Pin
None_Force26-May-09 0:53
None_Force26-May-09 0:53 
GeneralTrouble using the xsd command with SVG schema Pin
AmitDey30-Jul-08 21:02
AmitDey30-Jul-08 21:02 
Questionxsd C:\Emp.xsd /t:lib /l:cs /c [modified] Pin
MyronJames18-Jul-07 5:26
MyronJames18-Jul-07 5:26 
Generalnoice aRtickle !@! Pin
koms1613-Feb-07 22:10
koms1613-Feb-07 22:10 
GeneralStill More Generic Pin
asithangae24-May-06 0:06
asithangae24-May-06 0:06 
GeneralRe: Still More Generic (sample using Generics for .net 2.0 or later) Pin
contato.atsa31-Mar-08 2:23
contato.atsa31-Mar-08 2:23 
Thanks for the excelent article. Follow my contribution to an even more generic using Generics:

private string EntityToXml<T>(T entity)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.UTF8);
// get serialise object
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, entity); // 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);
UTF8Encoding utf = new UTF8Encoding(); // convert byte array to string
return utf.GetString(arr).Trim().Replace("\n", "").Replace("\r", ""); ;
}
catch
{
return string.Empty;
}
finally
{
if (stream != null) stream.Close();
if (writer != null) writer.Close();
}
}


private static T XmlToEntity<T>(string xml)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
// serialise to object
XmlSerializer serializer = new XmlSerializer(typeof(T));
stream = new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create reader
// covert reader to object
return (T)serializer.Deserialize(reader);
}
catch
{
return default(T);
}
finally
{
if (stream != null) stream.Close();
if (reader != null) reader.Close();
}
}

Use example:


string xml = EntityToXml<YourType>(Entity);

YourType entity = XmlToEntity<YourType>(xml)
GeneralSaved my day Pin
skjagini6-Sep-05 2:19
skjagini6-Sep-05 2:19 
GeneralCodeXS XSD-to-Code Generator Tool Pin
Willem Fourie25-May-05 23:49
Willem Fourie25-May-05 23:49 
GeneralVery cool!! Pin
Steven A Bristol19-May-05 2:47
Steven A Bristol19-May-05 2:47 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.