- Posted by Ian Suttle on December 10, 2007
- Filed under .Net Framework
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>