开发者

Custom Element Names using the DataContractSerializer on a List of primitives

开发者 https://www.devze.com 2023-02-22 00:17 出处:网络
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

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&开发者_StackOverflow中文版lt;/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!


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; }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消