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

折月煮酒 提交于 2019-12-10 20:00:06

问题


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>

回答1:


Why on earth are you doing this??

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

I don't think the KnownType attribute is needed here - it would be needed in polymorphism cases: if you have a method that returns BaseType and could return a derived type Type1 : BaseType in its place.

If you return Type1 and you'll only ever really have Type1 as the type, that knownType attribute is superfluous.

The second problem is this:

public class MyStuff : Collection<object> {

If you have a collection of object - it's a collection of potentially anything at all - so the serializer will use the xs:anyType to represent that.

Can't you introduce a base class type, make your collection a collection of that base type, and derive your two separate types from that base class?



来源:https://stackoverflow.com/questions/2912687/how-to-use-datacontractserializer-to-create-xml-with-tag-names-that-match-my-kno

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