How to exclude class fields from serialization by XmlElement name?-Collection of common programming errors
Have you encountered the [XmlIgnore] attribute? Adding it to members of your class will exclude them from serialization.
So, for example, you can replace [XmlElement("Surname")] with [XmlIgnore], and then your serialized agent will look like this:
John Doe
Alternately, if all you really want is just John Doe, you could write a wrapper class:
[XmlRoot("Name")]
public class NameElement
{
[XmlText]
public string Name { get; set; }
}
* EDIT *
While it’s possible to generate such wrappers at runtime, it’s difficult, inefficient, and not very practical.
To do so, I guess you could reflectively examine your object and find the properties you want (root.GetType().GetProperties().Where(p => /* your logic here */)), and use System.Reflection.Emit to generate the appropriate class. While possible, it’s not reasonable – it’d be a huge amount of code relative to your actual logic, and you could easily destabilize the runtime and/or leak memory.
A better way to achieve the dynamicism you want is to forego System.Xml.Serialization and use System.Xml.Linq. This would require you to write code that built up the xml yourself, but it’s super easy:
public XElement ConvertToXml(RootClass root)
{
return new XElement("Name", root.Name);
}
You can write an XElement to any stream using the element.Save(Stream) instance method on XElement.
Read more about Linq to XML at MSDN