Mushon
Mushon

Reputation: 21

Serialization of Classes with modification in .net 2.0

lets say I have this model

class Color
{
    string name;
    string type;
}

Class ColorsList
{
List<Color>;
}

and I need to populate those classes to xml

<ColorsList>
    <Color>red
        <type>brush</type>
    </Color>
    <Color>blue
        <type>spray</type>
    </Color>
</ColorsList>

I cant change my classes structure cause in that way I can bind it to a grid control.

what is the best practice for such a thing? is there a simple way to do that? I was thinking of creating a different model for the xml..

Upvotes: 0

Views: 73

Answers (2)

Vadim
Vadim

Reputation: 2865

Both XmlSerializer and DataContractSerializer can be used if the properties are public. They will create a larger and uglier XML than you described.

If you must serialize non public properties, you can still use DataContractSerializer (Can an internal setter of a property be serialized?).

Usage examples -

http://msdn.microsoft.com/en-us/library/bb675198.aspx

http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm

2 Notes -

  1. These serializers are slow - that should not be an issue if you save dozens or hundreds of them. If you plan to handle LOTS of these items - it might become an issue. You could use binary serializers (those in .net \ protobuf.net \ protosharp) or write your own XML serializers.
  2. You presentation layer should not depend on the way you store your data and the opposite. If these two affect each other - your design may be too coupled.

UPDATE

Just noticed the .net 2.0 restriction. DataContractSerializer requires .net 3.0 and above.

Upvotes: 1

Ralf
Ralf

Reputation: 1352

Strip the XmlWriterSettings and XmlSerializerNamespaces out of the example if thats not really relevant.

public class Color
{
    [XmlText]
    public string Name { get; set; }
    [XmlElement(ElementName = "type")]
    public string Type { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Color> colorlist = new List<Color>();
        colorlist.Add(new Color() { Name = "red", Type = "brush" });
        colorlist.Add(new Color() { Name = "blue", Type = "spray" });

        XmlWriterSettings xws = new XmlWriterSettings();            
        xws.OmitXmlDeclaration = true;
        xws.Encoding = Encoding.UTF8;
        xws.Indent = true;

        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        StringBuilder output = new StringBuilder();
        using(var wr = XmlWriter.Create(output, xws))
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Color>), new XmlRootAttribute("ColorsList"));
            ser.Serialize(wr, colorlist, ns);
        }

        Console.WriteLine(output.ToString());
        Console.ReadLine();
    }
}

Upvotes: 0

Related Questions