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

Consider the following XML:

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

I have the following code:

  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 cannot deserialize treelink objects, in foo TreeLinks always remains null.

What am I doing wrong here?

thanks

+4
source share
1 answer

Use an XmlElement in the list of tree links.

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

Using [XmlArray] and [XmlArrayItem] implies that you want tree references in their own container container inside the parent class - in other words, it expects xml as follows:

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

The trick here always starts in a different direction. Mark the class to serialize, and then serialize the instance of your type and look at the xml it created. You can then tweak it until it looks like xml, which you ultimately want to deserialize. This is a lot easier than trying to guess why your XML is not being deserialized correctly.

+7
source

Source: https://habr.com/ru/post/1397429/


All Articles