我在使用这种结构反序列化元素列表中的列表时遇到问题:
<Level>
<Stage>
<Sets>
<Set></Set>
<Set></Set>
</Sets>
</Stage>
<Stage>
<Sets>
<Set></Set>
<Set></Set>
</Sets>
</Stage>
</Level>
我目前的代码是:
public class Level{
[XmlElement(ElementName="Stage")]
public List<Stage> Stages = new List<Stage>();
}
public class Stage{
[XmlAttribute("label")]
public string label {get;set;}
[XmlAttribute("pack")]
public string pack {get;set;}
[XmlElement(ElementName = "Sets")]
public List<Set> Sets = new List<Set>();
}
public class Set{
[XmlAttribute("pick")]
public string pick {get;set;}
[XmlAttribute("type")]
public string type {get;set;}
[XmlAttribute("count")]
public int count {get;set;}
}
我正在使用此示例文档进行测试:
<?xml version="1.0"?>
<Level>
<Stage id="0" label="Debug Stage 1" pack="debugpack">
<Sets type = "this should not be displayed" >
<Set type="obstacles" pick="random" count="8" ></Set>
<Set type="combat" pick="list" count="8" >
<Piece id="1"><mod value="no-turret"/></Piece>
<Piece id="2"><mod value="no-fly"/></Piece>
</Set>
<Set type="boss" pick="random" count="inf" ></Set>
</Sets>
</Stage>
<Stage id="1" label="Debug Stage 2" pack="debugpack">
.... similar information here ...
</Stage>
</Level>
如何正确注释List&lt;&gt;等级和阶段的属性?
答案 0 :(得分:6)
您的Level
课程看起来不错。
您的Stage
课程需要如下所示:
public class Stage
{
[XmlAttribute("label")]
public string label { get; set; }
[XmlAttribute("pack")]
public string pack { get; set; }
[XmlArray("Sets")]
[XmlArrayItem("Set")]
public List<Set> Sets = new List<Set>();
}
您告诉反序列化器数组本身被称为“集合”,并且数组中的项称为“Set”。
还有一件事 - 由于行:
,您的XML将无法加载<Set type="boss" pick="random" count="inf" ></Set>
count
字段必须是整数 - 将其更改为数字,并且您的文件应该正常加载。