0

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
Shankar
  • 841
  • 1
  • 13
  • 39
  • http://stackoverflow.com/questions/2339782/xml-serialization-and-namespace-prefixes maybe this will help – Doro Nov 06 '15 at 13:26

1 Answers1

3

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>
Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26