将派生类根序列化为具有类型的基类名称

将派生类根序列化为具有类型的基类名称

本文介绍了将派生类根序列化为具有类型的基类名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知何故无法实现此序列化.我有这些课

I am somehow not able to achieve this serialization. I have these classes

public class Data
{
    [XmlElement("Name")]
    public string Name { get; set; }
}

[XmlRoot("Data")]
public class DataA : Data
{
    [XmlElement("ADesc")]
    public string ADesc { get; set; }
}

[XmlRoot("Data")]
public class DataB : Data
{
    [XmlElement("BDesc")]
    public string BDesc { get; set; }
}

当我序列化 DataA 或 DataB 时,我应该得到以下结构中的 XML:

When I serialize either DataA or DataB I should get the XMLs in the below structure:

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataA">
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
</Data>

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="" i:type="DataB">
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
</Data>

我得到的是以下内容(没有 i:type="..." 和 xmlns="")

What I am getting is the below (without the i:type="..." and xmlns="")

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
</Data>

<Data xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
</Data>

我不确定我在这里遗漏了什么.任何建议都会有所帮助.

I am not sure what I am missing here. any suggestions would be helpful.

  • 吉里哈

推荐答案

您应该包括基类的 XML 序列化的派生类型.

You should include the derived types for XML Serialization of the base class.

然后你可以为基类型创建一个序列化器,当你序列化任何派生类型时,它会添加类型属性:(你现在甚至可以从派生类中删除[Root] sttribute)

Then you can create a serializer for the base type, and when you serialize any derived type, it will add the type attribute: (You can even remove the [Root] sttribute from the derived classes now)

[XmlInclude(typeof(DataA))]
[XmlInclude(typeof(DataB))]
[XmlRoot("Data", Namespace = Data.XmlDefaultNameSpace)]
public class Data
{
    public const string XmlDefaultNameSpace = "http://www.stackoverflow.com/xsd/Data";

    [XmlElement("Name")]
    public string Name { get; set; }
}

序列化:

DataA a = new DataA() { ADesc = "ADesc", Name = "A" };
DataB b = new DataB() { BDesc = "BDesc", Name = "B" };
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), a);
new XmlSerializer(typeof(Data)).Serialize(Console.OpenStandardOutput(), b);

这是DataA类序列化的输出

Here is the output for DataA class serialization

<?xml version="1.0"?>
<Data xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:type="DataA" xmlns="http://www.stackoverflow.com/xsd/Data">
  <Name>A</Name>
  <ADesc xmlns="">ADesc</ADesc>

这篇关于将派生类根序列化为具有类型的基类名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:19