What is the easiest way to convert this XML document to my object?

后端 未结 2 1311
盖世英雄少女心
盖世英雄少女心 2021-01-05 15:49

I have an XMLDocument that i need to read in and convert into a set of objects. I have the following objects

public class Location
{
      public string Nam         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 16:39

    You could start by fixing your XML because in the example you have shown you have unclosed tags. You might also wrap the tags into a collection in order to be able to have other properties in this Location class other than buildings.

    
    
      
        
          
            
              
                
                  18
                
                
                  6
                
              
            
    
            
              
                
                  18
                
              
            
          
        
        
          
            
              
                
                  6
                
              
            
          
        
      
    
    

    Once you have fixed your XML you could adapt your models. I would recommend you using properties instead of fields in your classes:

    public class Location
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
    
        public List Buildings { get; set; }
    }
    
    public class Building
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
        public List Rooms { get; set; }
    }
    
    public class Room
    {
        [XmlAttribute("name")]
        public string Name { get; set; }
        public int Capacity { get; set; }
    }
    
    [XmlRoot("info")]
    public class Info
    {
        [XmlArray("locations")]
        [XmlArrayItem("location")]
        public List Locations { get; set; }
    }
    

    and now all that's left is deserialize the XML:

    var serializer = new XmlSerializer(typeof(Info));
    using (var reader = XmlReader.Create("locations.xml"))
    {
        Info info = (Info)serializer.Deserialize(reader);
        List locations = info.Locations;
        // do whatever you wanted to do with those locations
    }
    

提交回复
热议问题