ToXml Extension Method in .NET 3.5

by Cameron Albert 27. February 2008 22:07

I built the following extension method in .NET 35. to XML serialize objects; thought it might be useful for someone else. I use to serialize collections to pass XML data to my stored procedures that save player skills and items in my PBBG engine.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace WebTools
{
public static class XmlHelper
    {
public static string ToXml(this object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}
}
}

I wrote another extension method specific to retrieving the modified values of a collection. You have to control when the IsDirty flag is set yourself but my properties take care of that.

public interface IModifiable
    {
bool IsDirty { get; }
void MarkClean();
void MarkDirty();
}

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WebTools
{
public static class ModifierHelpercs
    {
public static List<TSource> Modified<TSource>(this IEnumerable<TSource> source) where TSource : IModifiable
        {
return (from s in source where s.IsDirty select s).ToList();
}
}
}

Tags: , , , ,

ASP.NET Development | Game Development | General

Comments

Powered by BlogEngine.NET 1.5.0.7
Modified Theme by Mads Kristensen

About the Author

CameronAlbert.com I am Senior Software Development Consultant specializing in Silverlight, WPF and the Microsoft .NET Framework. 

I have released an iPhone game called the Adventures of Puppyman that was built using ExEn and am currently working on a WP7 and iPhone version of Perenthia soon to be released.

View Cameron Albert's profile on LinkedIn
See how we're connected

Follow cameronalbert on Twitter

 

Recommended Books

Silverlight 4 Business Application Development - Beginner's Guide:

http://www.packtpub.com/microsoft-silverlight-4-business-application-development-beginners-guide/book

Microsoft Silverlight 4 Business Application Development: Beginner’s Guide