如何反序列化,那里的小朋友是直接在根对象的列表小朋友、对象、直接、序列化

2023-09-04 11:31:06 作者:活着就是折腾

考虑下面的XML:

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

我有以下的code设置:

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

不过,我不能够反序列化treelink对象,在的TreeLinks始终保持为空。

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

我在做什么错在这里?

What am I doing wrong here?

感谢

推荐答案

使用的XmlElement 上树链接的名单。

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

使用 [XmlArray] [XmlArrayItem] 意味着要树链接在自己的包装容器内父类 - 换句话说,预计这样的XML:

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>

这里的窍门是始终在另一个方向出发。标记你的类进行序列化,然后序列化类型的实例,看看它生成的XML。然后,您可以调整它,直到它看起来像你最终要反序列化的XML。这是不是试图去猜测为什么你的XML不是正确的反序列化更容易。

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.

 
精彩推荐