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

I have the following 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; }
}

What I serialize in 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 resulting xml string is as follows:

<?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 make it use the name of my known types instead, and not anyType in the xml tag?

I want 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>
+3
source share
1 answer

Why are you doing this?

[DataContract(Name = "Type1")]
[KnownType(typeof(Type1))]
public class Type1
{
}

I don’t think that an attribute KnownTypeis needed here - it will be needed in cases of polymorphism: if you have a method that returns BaseTypeand can return a derived type Type1 : BaseTypein its place.

Type1, Type1 , knownType .

:

public class MyStuff : Collection<object> {

object - - , xs:anyType .

, ?

+1

Source: https://habr.com/ru/post/1747184/


All Articles