Serialize derived class root as base class name with type

天大地大妈咪最大 提交于 2019-12-13 07:13:08

问题


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; }
}

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>

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.

  • Girija

回答1:


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

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; }
}

Serialization:

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);

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>


来源:https://stackoverflow.com/questions/33567824/serialize-derived-class-root-as-base-class-name-with-type

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