How to serialize an included object/property as a root?

回眸只為那壹抹淺笑 提交于 2019-12-25 08:28:04

问题


I've got a tough problem. Let's say I have a class named ObjectHost, containing a property of type BusinessObject, which itself contains some properties (let's say a Name and a Town as strings). The code would be :

public class ObjectHost
{
    public BusinessObject Data { get; set; }

    public ObjectHost()
    {
        Data = null;
    }

    public ObjectHost(BusinessObject ei)
    {
        Data = ei;
    }

    public override string ToString()
    {
        return (Data == null) ? "null" : Data.ToString();
    }
}

When serializing, it will produce something like :

<ObjectHost>
  <Data>
    <Name>My name</Name>
    <Town>London</Town>
  </Data>
</ObjectHost>

Where I'd like it to be :

<Name>My name</Name>
<Town>London</Town>

as it is only an encapsulation object in my particular use (for some other purposes).

I tried using XmlRoot and XmlElement attributes but I didn't achieve my goal.

Is there a solution for this ?


回答1:


As I have understood, you are using XmlSerializer to serialize an Object.

You are passing in ObjectHost and want only properties of ObjectHost.BusinessObject to be emitted.

You can use one of the following approaches

  1. Post processing of serialized data -> use XPath queries to get desired data

    /ObjectHost/Data
    
  2. Customize serialize process: (This is little tricky)
    a) Implement IXmlSerializable
    b) Customize ReadXml, WriteXml, and GetSchema

    In the WriteXml, use XPath query, or other Xml methods (to get XmlNodes) and write only desired properties.
    This approach will be tied to particular data structure, and cannot be used for incompatible data structure.



来源:https://stackoverflow.com/questions/10723302/how-to-serialize-an-included-object-property-as-a-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!