Using XmlSerializer with an array in the root element

前端 未结 1 540
别那么骄傲
别那么骄傲 2020-12-03 06:38

I have an XML document similar to the following:


    
        ...
    &         


        
      
      
      
1条回答
  •  -上瘾入骨i
    2020-12-03 07:17

    You should use [XmlElement], and not [XmlArray] to decorate the Items property - it's already an array, and you only want to set the element name.

    public class StackOverflow_12924221
    {
        [XmlRoot("scan_details")]
        public class ScanDetails
        {
            [XmlElement("object")]
            public ScanDetail[] Items { get; set; }
        }
    
        public class ScanDetail
        {
            [XmlAttribute("name")]
            public string Filename { get; set; }
        }
    
        const string XML = @" 
                                 
                                 
                                 
                                 
                             ";
    
        public static void Test()
        {
            XmlSerializer xs = new XmlSerializer(typeof(ScanDetails));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(XML));
            var obj = xs.Deserialize(ms) as ScanDetails;
            foreach (var sd in obj.Items)
            {
                Console.WriteLine(sd.Filename);
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题