简体   繁体   中英

Xml Deserialization - Sequence of Mutiple Types

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

<Values>
   <Links>
      <ImageLink>http://#</ImageLink>
      <ImageLink>http://#</ImageLink>
      <DocumentLink>http://#</DocumentLink>
   </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.

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; }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM