Deserialization of xml file by using XmlArray?

后端 未结 1 1315
北恋
北恋 2020-12-09 11:18

I am trying to deserialize this xml structure.



    
        Test
             


        
相关标签:
1条回答
  • 2020-12-09 11:49

    You need a common type to be able to deserialize your XML, and with that you can define with the [XmlElement] namespace what type to instantiate depending on the name of the element, as shown below.

    public class StackOverflow_15907357
    {
        const string XML = @"<?xml version=""1.0""?>
                            <DietPlan>
                                <Health>
                                    <Fruit>Test</Fruit>
                                    <Fruit>Test</Fruit>
                                    <Veggie>Test</Veggie>
                                    <Veggie>Test</Veggie>
                                </Health>
                            </DietPlan>";
    
        [XmlRoot(ElementName = "DietPlan")]
        public class TestSerialization
        {
            [XmlArray("Health")]
            [XmlArrayItem("Fruit", Type = typeof(Fruit))]
            [XmlArrayItem("Veggie", Type = typeof(Veggie))]
            public Food[] Foods { get; set; }
        }
    
        [XmlInclude(typeof(Fruit))]
        [XmlInclude(typeof(Veggie))]
        public class Food
        {
            [XmlText]
            public string Text { get; set; }
        }
    
        public class Fruit : Food { }
        public class Veggie : Food { }
    
        public static void Test()
        {
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
            XmlSerializer xs = new XmlSerializer(typeof(TestSerialization));
            TestSerialization obj = (TestSerialization)xs.Deserialize(ms);
            foreach (var food in obj.Foods)
            {
                Console.WriteLine("{0}: {1}", food.GetType().Name, food.Text);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题