.NET: How To: Convert an object to XML string
In this article we will show you how to output an object's data to an XML string.

0 Comments   Posted by LazyAssCoder on Nov 10, 2008   715 Views   Report Abuse
Tags: XML, Object, MemoryStream, Serialization, XmlTextWriter, UTF8Encoding

Bookmark and Share

 If you want to write out the data that is stored in an object or custom object, here is a neat function that will output the object's data to an XML string.

VB.NET

Function ConvertObjectToXmlString(ByVal objectToConvert As Object) As String
    Dim ms As New System.IO.MemoryStream()
    Dim xs As New System.Xml.Serialization.XmlSerializer(objectToConvert.GetType())
    Dim xtw As New System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8)

    xs.Serialize(xtw, objectToConvert)
    ms = DirectCast(xtw.BaseStream, System.IO.MemoryStream)

    Return New UTF8Encoding().GetString(ms.ToArray())
End Function

 

C#

public string ConvertObjectToXmlString(object objectToConvert)
{
       System.IO.MemoryStream ms = new System.IO.MemoryStream();
       System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(objectToConvert.GetType());
       System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(ms, System.Text.Encoding.UTF8);

       xs.Serialize(xtw, objectToConvert);
       ms = (System.IO.MemoryStream)xtw.BaseStream;

       return new UTF8Encoding().GetString(ms.ToArray());
 }

 


Comments

Login or Register to add a comment.