简体   繁体   English

序列化包含自定义类的类

[英]Serializing a class containing a custom class

I want to serialize an object as xml that contains other custom classes. 我想将一个对象序列化为包含其他自定义类的xml。 From what I understand (I've been reading MSDN and SO mostly), the XmlSerializer doesn't take this into account. 据我了解(我一直在阅读MSDN和SO), XmlSerializer并未考虑到这一点。

This is the line that's confusing me: 这是让我感到困惑的行:

XML serialization serializes only the public fields and property values of an object into an XML stream. XML序列化仅将对象的公共字段和属性值序列化为XML流。 XML serialization does not include type information. XML序列化不包含类型信息。 For example, if you have a Book object that exists in the Library namespace, there is no guarantee that it will be deserialized into an object of the same type. 例如,如果库名称空间中存在Book对象,则不能保证将其反序列化为相同类型的对象。

Taken from MSDN, here 来自MSDN, 在这里

For example, I want to serialize an object of type Order , but it contains a list of Products , and each one contains an object of type Category : 例如,我要序列化一个Order类型的对象,但是它包含一个Products列表,并且每个对象都包含一个Category类型的对象:

class Order
{
    List<Product> products;
}

class Product
{
    Category type;
}

class Category
{
    string name;
    string description;
}

And I want my Order object to be serialized like so: 我希望我的Order对象像这样被序列化:

<Order>
    <Product>
        <Category Name="">
            <Description></Description>
        </Category>
    </Product>
    <Product>
        <Category Name="">
            <Description></Description>
        </Category>
    </Product>
<Order>

Does the XmlSerializer already do this? XmlSerializer已经做到了吗? If not, is there another class that does or do I have to define the serialization process myself? 如果不是,是否还有另一个我必须定义自己的序列化过程的类?

An Order can be seen as a list of Products, a Product as a list of Categories (because it can pertain to multiple categories). 订单可以视为产品列表,产品可以视为类别列表(因为它可以属于多个类别)。

You can try using 您可以尝试使用

//...
using System.Xml;
using System.Xml.Serialization;
//...

[XmlRoot("Order")]
public class Order
{
    [XmlArrayItem(ElementName = "Product", Type = typeof(Product))]
    public List<Product> Products;
}

public class Product
{
    [XmlArrayItem(ElementName = "Category", Type = typeof(Category))]
    public List<Category> Categories;
}

public class Category
{
    [XmlAttribute("Name")]
    public string name;

    [XmlElement("Description")]
    public string description;
}

The only trade-off is, that the <Products> and <Categories> (plural) tags will be visible, because the variables are named that way, but from a point of view of parsing the XML afterwards, that's not an issue. 唯一的权衡是, <Products><Categories> (多个)标记将可见,因为变量是以这种方式命名的,但是从随后解析XML的角度来看,这不是问题。 If any other fields show up in your XML that you don't want, you can have [XmlIgnore()] precede them. 如果您不想在XML中显示任何其他字段,则可以在它们前面[XmlIgnore()]

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

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