How would I do this using a simple example?
The simplest approach would be to keep the object and xml
representations in sync. You can still promote properties to the parent
by using a facade property and marking it as XmlIgnore. More complex
examples involve proxies (see the dictionary example), or custom
IXmlSerializable.
Marc
using System;
using System.IO;
using System.Xml.Serialization;
static class Program
{
static void Main()
{
Venue venue = new Venue
{
Name = "The place",
Address = new Address
{
Line1 = "Foo", Line2 = "Bar", PostCode="Zip"
}
};
XmlSerializer ser = new XmlSerializer(typeof(Venue));
StringWriter writer = new StringWriter();
ser.Serialize(writer, venue);
string xml = writer.ToString();
}
}
[Serializable]
public sealed class Venue
{
[XmlAttribute]
public string Name { get; set; }
public Address Address { get; set; }
// PostCode is a facade property
[XmlIgnore]
public string PostCode
{
get
{
return Address == null ? null : Address.PostCode;
}
}
}
[Serializable]
public sealed class Address
{
[XmlAttribute]
public string Line1 { get; set; }
[XmlAttribute]
public string Line2 { get; set; }
[XmlAttribute]
public string PostCode { get; set; }
}