Donald King's Blog

Implements IQuestionable

  Home  |   Contact  |   Syndication    |   Login
  3 Posts | 0 Stories | 3 Comments | 8 Trackbacks

News

Archives

Post Categories

AgileWise Articles

Technology Links

Monday, July 04, 2005 #

I have been trying to solve a little problem I have with controlling the serialization of a class I have inherited from CollectionBase to create a strongly typed collection. The class that drove the need for my strongly typed collection is of type HeadlinesArticle and the collection class is HeadlinesArticleCollection:
 
 
[XmlRootAttribute("Article")]
public class HeadlinesArticle
{
...
}
 
[XmlRootAttribute("Article")]
public class HeadlinesArticleCollection : CollectionBase
{
...
}

As you can see in above code, I have decorated the HeadlinesArticle class so that the serializer will write out 'Article' as the root. It works fine and produces exactly what I need. The HeadlinesArticleCollection class is somewhat different. As many of you know, the default serialization behavior for this type of class is to output something similar to this:
<ArrayOfHeadlinesArticle>
...
</ArrayOfHeadlinesArticle>
To change this behavior, I had to create a new System.Xml.Serialization.XmlRootAttribute and provide what root element I want the Serializer to use. Here's an example where 't' is of type HeadlinesArticleCollection:
 

serializer = new XmlSerializer(t, new System.Xml.Serialization.XmlRootAttribute("Articles"));

This is all fine except the Serializer ignores the root attribute decoration I placed on the HeadlinesArticle class and so instead of this:
<Articles>
<Article>
...
</Article>
<Article>
...
</Article>
<Article>
...
</Article>
</Articles>
I get this:
<Articles>
<HeadlinesArticle>
...
</HeadlinesArticle>
<HeadlinesArticle>
...
</HeadlinesArticle>
<HeadlinesArticle>
...
</HeadlinesArticle>
</Articles>

Obviously the Serializer is ignoring the root attribute I placed on the HeadlinesArticle class. So I tried using the [XmlElement] attribute on the indexer of HeadlinesArticleCollection class but it basically has no effect at all:
 


[XmlElement("Article")]
public int IndexOf( Article value )  
        {
            return( List.IndexOf( value ) );
        }

So my question is, does anyone have an idea of what I can do to get the behavior in serialization I need short of renaming the HeadlinesArticle class to Article? Renaming the class is of course a work-around but I sure hate to think that I can't name my classes what I want.

One other caveat is I considered implementing the IXmlSerializable interface which I have done before and it works but I feel I should not have to go to that length for this. Any help is appreciated.

DK

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati