views:

68

answers:

2

Given the following fragment where links is a sequence of unbounded imagelinks and documentlinks, what should the deserailized class be?

<Values>
   <Links>
      <ImageLink>http://#&lt;/ImageLink&gt;
      <ImageLink>http://#&lt;/ImageLink&gt;
      <DocumentLink>http://#&lt;/DocumentLink&gt;
   </Links>
</Values>

Typically, if it was just an array of imagelinks I might have

public class Values
{
   public imagelink[] ImageLinks { get; set; }
}

public class ImageLink
{
   public string Value { get; set; }
}

But with the above xml I'm stumped.

Btw, I have no control over the xml.

+1  A: 

You should have a base class Link as follows

public class Link
{
  public string Href { get; set; }
}

public class ImageLink : Link
{
}

public class DocumentLink : Link
{
}

And your values class would look like:

public class Values
{
   public Link[] links { get; set; }
}

Alternatively, you could use ArrayList instead of strong typed array.

Bill Yang
Not good enough. He'll also need explicit `[XmlElement]` declarations on `links` to let `XmlSerializer` know what derived types of `Link` are expected (and what the corresponding element names are).
Pavel Minaev
It was intended to answer the question "what class should it be?", but you have a valid point that answers need to work. I'll leave it as is since Jaimal Chohan has already posted working code.
Bill Yang
Cheers Bill and Pavel, although Bill's answer didn;t work, it did lead me in the right direction
Jaimal Chohan
+2  A: 

This worked

public class DocumentLink : Link
{
}

public class ImageLink : Link
{
}

public class Link
{
    [XmlText]
    public string Href { get; set; }
}

public class Values
{
    [XmlArrayItem(ElementName = "ImageLink", Type = typeof(ImageLink))]
    [XmlArrayItem(ElementName = "DocumentLink", Type = typeof(DocumentLink))]
    public Link[] Links { get; set; }
}
Jaimal Chohan