开发者

Another "preserve reference" XmlSerializer issue

开发者 https://www.devze.com 2023-04-04 15:13 出处:网络
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.

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:

开发者_开发百科
  1. 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)

  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消