简体   繁体   English

如何将包含的对象/属性作为根序列化?

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

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). 假设我有一个名为ObjectHost的类,其中包含BusinessObject类型的属性,该属性本身包含一些属性(例如,将NameTown作为字符串)。 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. 我尝试使用XmlRootXmlElement属性,但没有实现我的目标。

Is there a solution for this ? 有解决方案吗?

As I have understood, you are using XmlSerializer to serialize an Object. 据我了解,您正在使用XmlSerializer序列化对象。

You are passing in ObjectHost and want only properties of ObjectHost.BusinessObject to be emitted. 您正在传递ObjectHost,并且只希望发出ObjectHost.BusinessObject的属性。

You can use one of the following approaches 您可以使用以下方法之一

  1. Post processing of serialized data -> use XPath queries to get desired data 对序列化数据进行后期处理->使用XPath查询获取所需数据

     /ObjectHost/Data 
  2. Customize serialize process: (This is little tricky) 自定义序列化过程:(这有点棘手)
    a) Implement IXmlSerializable a)实现IXmlSerializable
    b) Customize ReadXml, WriteXml, and GetSchema b)自定义ReadXml,WriteXml和GetSchema

    In the WriteXml, use XPath query, or other Xml methods (to get XmlNodes) and write only desired properties. 在WriteXml中,使用XPath查询或其他Xml方法(以获取XmlNodes)并仅写入所需的属性。
    This approach will be tied to particular data structure, and cannot be used for incompatible data structure. 这种方法将与特定的数据结构相关联,并且不能用于不兼容的数据结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM