How to deserialize a list of objects where the chi

2019-06-23 22:48发布

Consider the following XML:

<?xml version="1.0" encoding="utf-8"?>
<treelist id="foo" displayname="display">
  <treelink id="link" />
</treelist>

I've got the following code set up:

    private static void Main(string[] args)
    {
        StreamReader result = File.OpenText(@"test.xml");

        var xmlTextReader = new XmlTextReader(result.BaseStream, XmlNodeType.Document, null);

        XDocument load = XDocument.Load(xmlTextReader);

        var xmlSerializer = new XmlSerializer(typeof (TreeList));

        var foo = (TreeList) xmlSerializer.Deserialize(load.CreateReader());
    }

And these are my entities:

[Serializable]
[XmlRoot("treelink")]
public class TreeLink
{
    [XmlAttribute("id")]
    public string Id { get; set; }
}

[Serializable]
[XmlRoot("treelist")]
public class TreeList
{
    [XmlAttribute("id")]
    public string Id { get; set; }

    [XmlAttribute("displayname")]
    public string DisplayName { get; set; }

    [XmlArray("treelist")]
    [XmlArrayItem("treelist", typeof (TreeLink))]
    public TreeLink[] TreeLinks { get; set; }
}

However I am not able to deserialize the treelink objects, in foo the TreeLinks always stays null.

What am I doing wrong here?

Thanks

1条回答
时光不老,我们不散
2楼-- · 2019-06-23 23:02

Use XmlElement on the "list" of tree links.

[XmlElement("treelink")]
public TreeLink[] TreeLinks { get; set; }

Using [XmlArray] and [XmlArrayItem] imply that you want the tree links in their own wrapping container within the parent class - in other words it expects xml like this:

<treelist id="foo" displayname="display">
  <treelist>
    <treelist id="link" />
  </treelist>
</treelist>

The trick here is always to start off in the other direction. Mark up your class for serialization and then serialize an instance of your type and look at the xml it generates. You can then tweak it until it looks like the xml you ultimately want to deserialize. This is much easier than trying to guess why your xml isn't deserializing correctly.

查看更多
登录 后发表回答