Custom Element Names using the DataContractSerializer on a List of primitives

こ雲淡風輕ζ 提交于 2021-02-04 14:52:07

问题


I'm interested about the best way to go about setting custom element names when using List of primitives with the DataContractSerializer. Let's say I have the following class which contains a List of Strings as a DataMember.

[DataContract]
public class ClassName
{
    [DataMember]
    public List<String> FieldName { get; set; }
}

By default, this serializes to the following:

<ClassName xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <FieldName xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:string>Value 1</a:string>
    <a:string>Value 2</a:string>
    <a:string>Value 3</a:string>
  </FieldName>
</ClassName>

I would like to make the XML as simple as possible to transform via XSLT so ideally I would rename the tags into something more useful, like Value.

One possible solution involves creating a class that extends Collection and setting the ItemName for the CollectionDataMember parameter, which I found here. I was wondering if there was a way to accomplish the same goal without the need for a this extra class or other form of wrapper class. The XML serializer makes use of XMLArray and XMLArrayItem parameters to accomplish this but the DataContractSerializer does not appear to have similar functionality.

Thanks for any tips or ideas!


回答1:


Define data contract to represent list of strings and use it as a type for your FieldName property. Then you can use CollectionDataContract attribute to customize XML.

[CollectionDataContract(ItemName="Value")]
public class MyList : List<string>  {}

[DataMember]
public MyList FieldName { get; set; }



回答2:


Your options are limited. DataContractSerializer is not designed to produce beautiful XML. It's used by WCF which is not human eye friendly in nature. So the most you can do is minimize namespace use and name elements by defining custom type with a string property.



来源:https://stackoverflow.com/questions/5516907/custom-element-names-using-the-datacontractserializer-on-a-list-of-primitives

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