Another "preserve reference" XmlSerializer issue
I´m working on a "new language" (not such ambitious) XML definition, I want to have the option to work with object graph vía xml (serializing/deserializing) and API at same time.
public class Project
{
public List<Connection> Connections { get; set; }
public List<Table> Tables { get; set; }
/* Constructors and more.... */
}
public class Connection
{
public string Name { get; set; }
public string ConnectionString { get; set; }
/* Constructors and more.... */
}
public class Table
{
public string TableName { get; set; }
public Connection Conn { get; set; }
/* Constructors and more.... */
}
OK, now I want to serialize/deserialize this with something like:
<Project>
<Connections>
<Connection Name="MyConnName" ConnectionString="My connection string"\>
<\Connections>
<Tables>
<Table TableName="MyTable" ConnectionName="MyConnName"\>
<\Tables>
<\Project>
There are two issues here:
开发者_开发百科The class has a "Conn" property that is a reference to a Connection Class, but in the "language" (Xml serialization) is renamed to "ConnectionName" (I want to change the name avoiding confusion between pure Object reference (Class) and language "reference by name" (Xml seralization)
As you can see, I want to preserve reference, but no including "z.id ??" like DataContractSerializer does when preserveObjectReference is set to true, instead I want to use "names" (much more human readable)
Any ideas?
There's really no good way to extend XmlSerializer
to do what you want, for almost any useful value of 'what you want'.
To generate the sort of XML you're looking for, you'll have to decorate the Connection
property with [XmlIgnore]
, add a ConnectionName
property for the XmlSerializer to use, and locate the appropriate Connection
either when ConnectionName
is set or sometime after.
Alternatively, you'll need to have Table
implement IXmlSerializable
and completely hand-implement the code that generates the <Table>
element.
精彩评论