How to use XmlElementAttribute for List <T>?

I have a class like this:

public class Level { [XmlAttribute] public string Guid { get; set; } } public class LevelList : List<Level> { } public class Test { public LevelList CalLevelList { get; set; } } 

Using XmlSerializer, I get the output as follows:

  <CalLevelList> <Level Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/> <Level Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/> </CalLevelList> 

This is technically correct. However, without changing the class names, I would like to conclude this way:

  <Levels> <L Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/> <L Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/> </Levels> 

I know that this can be done using attributes, but could not figure out how to do it. When I add an attribute of the Test class as follows:

  public class Test { [XmlElement("Levels")] public LevelList CalLevelList { get; set; } } 

the conclusion is quite surprising:

 <Levels Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/> <Levels Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/> 

This means that I lost the parent node. The specified element name becomes the node name. Why is this? how to make it work?

+7
source share
1 answer

Try the following:

 public class Test { [XmlArray("Levels")] [XmlArrayItem("L")] public LevelList CalLevelList { get; set; } } 
+14
source

All Articles