Deserialize List object

后端 未结 2 1181
滥情空心
滥情空心 2021-01-20 05:46

I am trying to de-serialize a XML to object but I am getting stuck at one situation. Can anyone please help me out here.

XML:



        
2条回答
  •  迷失自我
    2021-01-20 06:14

    Change your LData class to this:

    [XmlRoot("Level")]
    public class LData
    {
        [XmlElement("Warp_Blocks")]
        public List WarpBlocks;
    }
    

    EDIT:
    I don't know why it is not reading your second Warp_Block. The only possible reason I think can be that you are doing something else than what you have posted in the question. Here is the full example:

    [XmlRoot("Level")]
    public class LData
    {
        [XmlElement("Warp_Blocks")]
        public List WarpBlocks;
    }
    public class LBlock
    {
        [XmlAttribute("row")]
        public int row;
        [XmlAttribute("col")]
        public int col;
    }
    public class WarpBlock
    {
        [XmlArray("Warp_Block")]
        [XmlArrayItem("Block", typeof(LBlock), IsNullable = false)]
        public List WarpBlocks;
    
        public WarpBlock()
        {
            WarpBlocks = new List();
        }
    }
    public class Program
    {
        public static void Main()
        {
            string test =
                "" +
                "" +
                "  " +
                "        " +
                "            " +
                "            " +
                "        " +
                "        " +
                "            " +
                "            " +
                "        " +
                "  " +
                "";
    
            byte[] byteArray = Encoding.ASCII.GetBytes(test);
            MemoryStream stream = new MemoryStream(byteArray);
    
            XmlSerializer s = new XmlSerializer(typeof (LData));
            LData data = (LData) s.Deserialize(stream);
    
            foreach (var a in data.WarpBlocks)
                foreach (var b in a.WarpBlocks)
                    Console.WriteLine(b.row + ", " + b.col);
    
            Console.ReadKey();
        }
    }
    

    It correctly outputs this:

    7, 7
    2, 7
    4, 4
    3, 7
    

提交回复
热议问题