ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

SerializeToXml

Serializes objects to an xml string. (Does not provide error handling if the object is not serializable.)

Source

public static string SerializeToXml(this object obj)
{
	XDocument doc = new XDocument();
	using(XmlWriter xmlWriter = doc.CreateWriter())
	{
		XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
		xmlSerializer.Serialize(xmlWriter, obj);
		xmlWriter.Close();
	}
	return doc.ToString();
}

Example

string hi = "hellow world";
string xml = hi.SerializeToXml();
Console.WriteLine(xml);

Output:

<string>hellow world</string>

Author: asawyer

Submitted on: 8 jul. 2010

Language: C#

Type: System.Object

Views: 8737