如何对 List使用 XmlElementAttribute?
我有一个这样的类:
public class Level
{
[XmlAttribute]
public string Guid { get; set; }
}
public class LevelList : List<Level>
{
}
public class Test
{
public LevelList CalLevelList { get; set; }
}
使用 XmlSerializer,我得到如下输出:
<CalLevelList>
<Level Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/>
<Level Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/>
</CalLevelList>
这在技术上是正确的。但是,在不更改类名的情况下,我想让输出看起来像这样:
<Levels>
<L Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/>
<L Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/>
</Levels>
我知道这可以通过属性来完成,但不知道如何实现。当我向 Test 类添加一个属性时,如下所示:
public class Test
{
[XmlElement("Levels")]
public LevelList CalLevelList { get; set; }
}
输出非常令人惊讶:
<Levels Guid="0de98dfb-ce06-433f-aeae-786b6d920aa6"/>
<Levels Guid="0de98dfb-ce06-433f-aeae-786b6d920aa7"/>
这意味着我丢失了父节点。我指定的元素名称成为节点名称。为什么会这样?如何让它发挥作用?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
Try this: