How to use DataContractSerializer to create xml with tag names that match my known types

Posted by mezoid on Stack Overflow See other posts from Stack Overflow or by mezoid
Published on 2010-05-26T11:59:13Z Indexed on 2010/05/26 12:01 UTC
Read the original article Hit count: 399

I have the following data contract:

[CollectionDataContract(Name="MyStuff")] 
public class MyStuff : Collection<object> {}

[DataContract(Name = "Type1")]
[KnownType(typeof(Type1))]
public class Type1
{
    [DataMember(Name = "memberId")] public int Id { get; set; }
}

[DataContract(Name = "Type2")]
[KnownType(typeof(Type2))]
public class Type2
{
    [DataMember(Name = "memberId")] public int Id { get; set; }
}

Which I serialize to xml as follows:

MyStuff pm = new MyStuff();

Type1 t1 = new Type1 { Id = 111 };
Type2 t2 = new Type2 { Id = 222 };

pm.Add(t1);
pm.Add(t2);

string xml;

StringBuilder serialXML = new StringBuilder();
DataContractSerializer dcSerializer = new DataContractSerializer(typeof(MyStuff));
using (XmlWriter xWriter = XmlWriter.Create(serialXML))
{
    dcSerializer.WriteObject(xWriter, pm);
    xWriter.Flush();
    xml = serialXML.ToString();
}

The resultant xml string looks like this:

<?xml version="1.0" encoding="utf-16"?>
<MyStuff xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://schemas.datacontract.org/2004/07/">
    <anyType i:type="Type1">
        <memberId>111</memberId>
    </anyType>
    <anyType i:type="Type2">
        <memberId>222</memberId>
    </anyType>
</MyStuff>

Does anyone know how I can get it to instead use the name of my known types rather than anyType in the xml tag?

I'm wanting it to look like this:

<?xml version="1.0" encoding="utf-16"?>
<MyStuff xmlns:i="http://www.w3.org/2001/XMLSchema-instance" 
         xmlns="http://schemas.datacontract.org/2004/07/">
    <Type1>
        <memberId>111</memberId>
    </Type1>
    <Type2>
        <memberId>222</memberId>
    </Type2>
</MyStuff>

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET