如何使用XmlElementAttribute的名单,其中,T>?如何使用、名单、XmlElementAttribute、GT

2023-09-03 06:52:03 作者:一世回眸万千情

我有一类这样的:

public class Level
{
    [XmlAttribute]
    public string Guid { get; set; }
}

public class LevelList : List<Level>
{
}

public class Test
{
    public LevelList CalLevelList { get; set; }
}

使用XmlSerializer的,我得到这样的输出:

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"/>

这意味着,我失去了父节点。我指定的ElementName成为一个节点名称。为什么这个?如何使它工作?

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

推荐答案

试试这个:

public class Test
{
    [XmlArray("Levels")]
    [XmlArrayItem("L")]
    public LevelList CalLevelList { get; set; }
}
 
精彩推荐
图片推荐