Custom Element Names using the DataContractSerializer on a List of primitives
Asked Answered
S

2

10

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!

Stipend answered 1/4, 2011 at 17:44 Comment(2)
Another option could be that you create a class called "Value : String" which inherits from System.String and use that in the DataMember ...Horner
@NabheetSandhu System.String is sealed. You cannot inherit from it.Butter
S
7

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; }
Salacious answered 16/4, 2013 at 3:30 Comment(1)
+1 - I didn't know how to do this. However, I recently needed to do this and went from XSD to DataContract using svcutil. This is pretty much what svcutil produced.Horner
S
0

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.

Surfperch answered 26/3, 2013 at 5:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.