0

I'm trying to deserialize a list of RShortcut objects, which is an abstract class. However, XmlSerializer always returns an empty list.

Here's the code I'm running:

String toolbarPath = HttpRuntime.AppDomainAppPath + Settings.Default.DEFAULT_TOOLBAR_PATH;
StreamReader reader = new StreamReader(toolbarPath);
XmlSerializer toolbarSerializer = new XmlSerializer(typeof(List<RShortcut>), new XmlRootAttribute("Shortcuts"));
List<RShortcuts> shortcuts = (List<RShortcut>)toolbarSerializer.Deserialize(reader);

These are the classes' definitions:

[Serializable]
[XmlRoot("Shortcut")]
[XmlType("Shortcut")]
[XmlInclude(typeof(RShortcutPopup))]
[XmlInclude(typeof(RShortcutTab))]
public abstract class RShortcut
{
    [XmlAttribute("path")]
    public String Path{ get; set; }
}

[Serializable]
[XmlRoot("Popup")]
[XmlType("Popup")]
public class RShortcutPopup : RShortcut
{
}

[Serializable]
[XmlRoot("Tab")]
[XmlType("Tab")]
public class RShortcutTab : RShortcut
{
}

And here's an xml example:

<Shortcuts>
  <Tab path="foo.bar.com" />
  <Popup path="foo.bar.net"/>
</Shortcuts>

What's the proper way to do it?

minusnine
  • 85
  • 10
  • The class names and the XML Element names have to match or add an attribute with the element name. Your xml has the element name "Shortcuts", but it is not a class name nor in any of the attributes (in square brackets). – jdweng Jan 23 '19 at 13:40
  • That's why I added "new XmlRootAttribute("Shortcuts")" as a parameter for the XmlSerializer constructor. "Shortcuts" is the root of the list – minusnine Jan 23 '19 at 13:43
  • Putting it in the serialize object will not work. You need an association between the class name and the xml data. You only have "Shortcut" without the 's'. – jdweng Jan 23 '19 at 13:49
  • I don't think I'm following you. Again, I'm deserializing a List object. Since List is a generic class, I need to define a root in the serializer ("Shortcuts"). I'm doing exactly the same elsewhere in my code, only difference is I'm deserializing a list of a concrete class, and it works. Here's an example: https://stackoverflow.com/a/21778067/4081173 – minusnine Jan 23 '19 at 14:01

0 Answers0