How to deserialize a list of objects where the children are directly in the root

杀马特。学长 韩版系。学妹 提交于 2019-12-10 15:26:13

问题


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:


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.



来源:https://stackoverflow.com/questions/9362103/how-to-deserialize-a-list-of-objects-where-the-children-are-directly-in-the-root

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!