Xml Serialization with Generic Lists

I had an instance where I was using a custom class as a return value type in a web service.  This is a pretty typical scenario.  When a web service is consumed, you, as the author, may want to alter the names of the properties being returned and would do so as such:

[XmlElement("NewName")]
public string InternalName
{
   get { return "something here..."; }
}

When serialized you'd have an element of <NewName /> somewhere in there.

...or if you have a class being return

[XmlRoot("NewClassName")]
public class InternalClass
{
...

When serialized you'd have a root node of <NewClassName><OtherNode...

You get the picture, right?  So far so good.  Now let's complicate matters a bit (as complicated as it gets at least).  Say you want to return a generic list of InternalClass defined something like this:

public List<InternalClass> InternalClassList
{
   get {...

Using the XmlRoot attribute on the class no longer works.  You would see <InternalClass> instead of <NewClassName>  So how do you modify the name of the generic parent and it's children?  Treat it as an array!

[XmlArray("NewClassNames")]
[XmlArrayItem("NewClassName")]
public List<InternalClass> InternalClassList
{
   get {...

Once serialized you would have a favorable result such as:

<NewClassNames>
   <NewClassName />
   <NewClassName />
</NewClassNames>

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Related posts

Comments

December 10. 2007 02:42 AM

trackback

Trackback from DotNetKicks.com

Xml Serialization with Generic Lists

DotNetKicks.com

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

November 20. 2008 02:09 PM