【问题标题】:Deserializing nested lists with XmlSerializer使用 XmlSerializer 反序列化嵌套列表
【发布时间】:2014-07-23 06:35:54
【问题描述】:

我在反序列化具有这种结构的元素列表中的列表时遇到问题:

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

如何正确注释 Level 和 Stage 中的 List 属性?

【问题讨论】:

    标签: c# xml deserialization xml-deserialization


    【解决方案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>();
    }
    

    您是在告诉反序列化器,数组本身称为“Sets”,而数组中的项称为“Set”。

    还有一件事 - 你的 XML 不会加载,因为这条线:

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

    count 字段必须是整数 - 将其更改为数字,您的文件应该可以正常加载。

    【讨论】:

    • XmlArray 和 XmlArrayItem 注释使我不必为了保存另一个类的列表而声明一个类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多