如何将包含的对象/属性序列化为根? [英] How to serialize an included object/property as a root?

查看:44
本文介绍了如何将包含的对象/属性序列化为根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个棘手的问题.假设我有一个名为 ObjectHost 的类,它包含一个 BusinessObject 类型的属性,它本身包含一些属性(假设一个 Name 和一个 Town 作为字符串).代码将是:

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>

我希望它在哪里:

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

因为它只是我特定用途中的封装对象(用于其他一些目的).

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

我尝试使用 XmlRootXmlElement 属性,但没有达到我的目标.

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

有没有办法解决这个问题?

Is there a solution for this ?

推荐答案

据我所知,您正在使用 XmlSerializer 来序列化对象.

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

您正在传入 ObjectHost 并且只想发出 ObjectHost.BusinessObject 的属性.

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

您可以使用以下方法之一

You can use one of the following approaches

  1. 序列化数据的后处理 -> 使用 XPath 查询获取所需数据

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

/ObjectHost/Data

  • 自定义序列化过程:(这有点棘手)
    a) 实现 IXmlSerializable
    b) 自定义 ReadXml、WriteXml 和 GetSchema

  • Customize serialize process: (This is little tricky)
    a) Implement IXmlSerializable
    b) Customize ReadXml, WriteXml, and GetSchema

    在 WriteXml 中,使用 XPath 查询或其他 Xml 方法(以获取 XmlNode)并仅写入所需的属性.
    这种方法将绑定到特定的数据结构,不能用于不兼容的数据结构.

    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.

    这篇关于如何将包含的对象/属性序列化为根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆