Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

XML Serialization of an Object - C#

RSS
Modified on Mon, Mar 21, 2016, 10:37 AM by Administrator Categorized as XML, XSL, and XPath, ┬ĚNet Framework

Overview

This article demonstrates how to serialize an object to XML

Sample Code

var myObject = new MyClass();
var xs = new XmlSerializer(myObject.GetType());
string resultXml;

using (var sw = new StringWriter())
{
    xs.Serialize(sw, myObject);
    resultXml = sw.ToString();
}

Generic Methods

public static string SerializeToXml<T>(T input)
{
    var result = string.Empty;
    var xs = new XmlSerializer(typeof(T));

    using (var sw = new StringWriter())
    {
        xs.Serialize(sw, input);
        result = sw.ToString();
    }

    return CleanXml(result);
}

public static T DeserializeFromXml<T>(string inputXml)
{
    T result = default(T);
    var xs = new XmlSerializer(typeof(T));

    using (var sr = new StringReader(inputXml))
    {
        result = (T)xs.Deserialize(sr);
        sr.Close();
    }
    return result;
}
public static string CleanXml(string inputXml)
{
    var result = inputXml;

    if (result.StartsWith("<?xml "))
    {
        var pos = result.IndexOf(">", 6);
        result = result.Substring(pos + 1).Trim();
    }

    return result;
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.