XML Serialization

banner art

The following sample code demonstrates how to serialize an entity to an XML string.

Example

[C#]
using System.Xml.Serialization;
using System.Text;
using System.IO;

public static string ToString(object o) 
{
   StringBuilder sb = new StringBuilder();
   XmlSerializer serializer = new XmlSerializer(o.GetType());
   XmlRootAttribute root = new XmlRootAttribute(o.GetType().Name);
   root.Namespace = "https://schemas.microsoft.com/crm/2006/WebServices";

   TextWriter writer = new StringWriter(sb);
   serializer.Serialize(writer, o);

   return sb.ToString();
}

public static object ToObject(Type t, string s)
{
    XmlSerializer serializer = new XmlSerializer(t);
    TextReader reader = new StringReader(s);

    object o = null;
    try
    {
        o = serializer.Deserialize(reader);
    }
    catch (Exception e)
    {
        // Failed to convert XML to object.
    }
    return o;
}

Example

The following code snippet shows how to call the methods above to serialize an account entity instance to an XML string.

[C#]
// Set up the CRM service.
CrmService service = new CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Retrieve an account.
account acctR = (account)service.Retrieve(EntityName.account.ToString(),
                             acctGUID, new AllColumns());

// Call the serialization method.
string strAccount = ToString(acctR);

// Now convert that string back to an account object.
account myAcct= (account)ToObject(typeof(account), strAccount);

© 2007 Microsoft Corporation. All rights reserved.