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!
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With