If it is a direct map, you should just be able to use it directly, as long as the types as public and have public parameterless constructors, and the properties (including lists) are get/set.
If you need to tweak the names there is an XmlSerializer
constructor that allows you to specify all the attributes. This is ideal for your scenario, but you must cache and re-use the serializer if you use this constructor overload, otherwise you will leak memory (the dynamic assemblies are not collected).
Here's a full example that removes one property (XmlIgnore
), changes another to an attribute, and leaves a third as an element.
using System;
using System.IO;
using System.Xml.Serialization;
public class Foo
{
public int A { get; set; }
public string B { get; set; }
public int C { get; set; }
}
static class Program
{
static readonly XmlSerializer serializer;
static Program()
{
XmlAttributeOverrides or = new XmlAttributeOverrides();
or.Add(typeof(Foo), "A", new XmlAttributes { // change to an attrib
XmlAttribute = new XmlAttributeAttribute("tweaked")
});
or.Add(typeof(Foo), "B", new XmlAttributes {
XmlIgnore = true // turn this one off
});
// leave C as a default named element
serializer = new XmlSerializer(typeof(Foo), or);
}
static void Main()
{
Foo foo = new Foo { A = 123, B = "def", C = 456 }, clone;
string xml;
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, foo);
xml = sw.ToString();
}
using (StringReader sr = new StringReader(xml)) {
clone = (Foo)serializer.Deserialize(sr);
}
Console.WriteLine(xml);
Console.WriteLine();
Console.WriteLine(clone.A);
Console.WriteLine(clone.B);
Console.WriteLine(clone.C);
}
}
Note also that if you only need to change things at the type level (such as [XmlInclude]
) then you can do this via the partial class
that LINQ-to-SQL generates; for example:
namespace My.Dal.Namespace {
// add a type attribute to SomeEntity
[XmlInclude(typeof(SomeDerivedEntity))]
partial class SomeEntity { }
}