How to use XmlElementAttribute for List<T>?

淺唱寂寞╮ 提交于 2020-01-01 09:29:11

问题


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 like this:

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

Which is technically correct. However, without changing the class names, I'd like to make the output look like this:

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

I know this could be done through attributes, but couldn't figure out how. When I add an attribute to Test class like this:

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

the output is quite surprising:

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

That means, I lost the parent node. The elementname I specified becomes a node name. Why this? how to make it work?


回答1:


Try this:

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


来源:https://stackoverflow.com/questions/6462091/how-to-use-xmlelementattribute-for-listt

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