Deserializing nested lists with XmlSerializer

2019-08-03 17:19发布

问题:

I have a problem deserializing a list inside a list of elements with this structure:

<Level>
  <Stage>
    <Sets>
     <Set></Set>
     <Set></Set>
    </Sets>
  </Stage>
  <Stage>
    <Sets>
      <Set></Set>
      <Set></Set>
    </Sets>
  </Stage>
</Level>

My current code is this:

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

And I'm testing with this sample document:

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

How do I correctly annotate the List<> properties in Level and Stage ?

回答1:

Your Level class looks fine.

Your Stage class needs to look like this:

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

You are telling the Deserializer that the array itself is called 'Sets' and the items in the array are called 'Set'.

One more thing - your XML won't load, because of the line:

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

The count field must be an integer - change it to a number, and your file should load fine.