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();
}
}
}