jeudi 5 novembre 2015

XMLArray with different types but same element name and i:type attribute

Vote count: 0

I am trying to serialize some data I have into this XML format but not able to achive the same.

The Desired XML output is below:

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:i="http://ift.tt/ra1lAU">
  <Datas>
    <Data xmlns="" i:type="DataA">
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
    </Data>
    <Data xmlns="" i:type="DataB">
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
    </Data>
  </Datas>
</Root>

The Classes I created for serialization are as follows:

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

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

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

[XmlRoot("Root")]
public class Root
{
    [XmlArray("Datas")]
    [XmlArrayItem(Type = typeof(Data))]
    [XmlArrayItem(Type = typeof(DataA))]
    [XmlArrayItem(Type = typeof(DataB))]
    public List<Data> Datas { get; set; }
}

I use the below method for serializing:

internal static string Serialize(Root obj)
{
    var ns = new XmlSerializerNamespaces();
    ns.Add("i", "http://ift.tt/ra1lAU");

    XmlSerializer xmlSerializer = new XmlSerializer(typeof(Root));

    using (StringWriter textWriter = new StringWriter())
    {
        xmlSerializer.Serialize(textWriter, obj, ns);
        return textWriter.ToString();
    }
}

But the output I get is this (which is not correct):

<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:i="http://ift.tt/ra1lAU">
  <Datas>
    <DataA>
      <Name>A1</Name>
      <ADesc>Description for A</ADesc>
    </DataA>
    <DataB>
      <Name>B1</Name>
      <BDesc>Description for b</BDesc>
    </DataB>
  </Datas>
</Root>

asked 22 secs ago

This entry passed through the Full-Text RSS service - if this is your content and you're reading it on someone else's site, please read the FAQ at http://ift.tt/jcXqJW.



XMLArray with different types but same element name and i:type attribute

Aucun commentaire:

Enregistrer un commentaire