反序列化与XmlSerializer的嵌套的列表(Deserializing nested list

2019-10-20 05:58发布

我反序列化这个结构元素的列表内列表的问题:

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

如何正确地标注在水平和阶段的列表<>属性?

Answer 1:

你的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>();
}

你说的是解串器,阵列本身被称为“集”和数组中的项目被称为“设置”。

还有一两件事 - 你的XML不会加载,因为该行的,:

<Set type="boss" pick="random" count="inf" ></Set>

count字段必须是整数-它改变了许多,你的文件应该加载罚款。



文章来源: Deserializing nested lists with XmlSerializer