Reputation: 21
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
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 -
UPDATE
Just noticed the .net 2.0 restriction. DataContractSerializer requires .net 3.0 and above.
Upvotes: 1
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