Shawn Weisfeld

I find when I talk to myself nobody listens. - Shawn Weisfeld
posts - 365, comments - 180, trackbacks - 34

My Links


Shawn Weisfeld's Facebook profile

The views expressed in this blog are mine and mine alone, not that of my employer, Microsoft, or anyone else’s. No warrantee is given for the quality of any material on this site.


Post Categories

How to convert XML file in to a class file using c#?


An oldie but a goodie. I like the technique that “arjay” outlined in his codeguru post ( However he noted a problem with the arrays that XSD.exe creates, namely you have to check for null every time you want to iterate over them. In the post he suggests hand editing the generated code. I am not a big fan of that. You can easily use a partial class to avoid needing to hand edit the code. Or you can use an extension method to encapsulate the check for you.


public static List<T> ToNonNullList<T>(this T[] items)
    if (items == null)
        return new List<T>();

    return items.ToList();




So how do you get the xml in the first place, perhaps you have it in a string, or it might be coming from an URI. How about a little helper class that will Deserialize it for us. . . .


public class XSerializer
    public static T Load<T>(string uri)
        return LoadParse<T>(XDocument.Load(uri));

    public static T Parse<T>(string xml)
        return LoadParse<T>(XDocument.Parse(xml));

    private static T LoadParse<T>(XDocument xDoc)
        XmlSerializer serializer = new XmlSerializer(typeof(T));
        using (XmlReader reader = xDoc.CreateReader())
            return (T)serializer.Deserialize(reader);

Print | posted on Friday, April 1, 2011 7:53 PM |


No comments posted yet.

Post Comment

Please add 1 and 3 and type the answer here:

Powered by: