我有一个
XMLDocument,我需要读入并转换为一组对象.我有以下物品
public class Location { public string Name; public List<Building> Buildings; } public class Building { public string Name; public List<Room> Rooms; }
我有以下XML文件:
<?xml version="1.0" encoding="utf-8" ?> <info> <locations> <location name="New York"> <Building name="Building1"> <Rooms> <Room name="Room1"> <Capacity>18</Capacity> </Room> <Room name="Room2"> <Capacity>6</Capacity> </Room> </Rooms> </Building> <Building name="Building2"> <Rooms> <Room name="RoomA"> <Capacity>18</Capacity> </Room> </Rooms> </Building> </location> <location name ="London"> <Building name="Building45"> <Rooms> <Room name="Room5"> <Capacity>6</Capacity> </Room> </Building> </location> </locations> </info>
这样做的最佳方式是什么?我应该自动将xmldocument序列化到对象还是我需要解析每个元素并手动转换为我的对象?特别是,我试图弄清楚如何转换集合(位置,建筑物等).
将此XML文件转换为基本的最佳建议是什么?
List<Location>
对象?
解决方法
您可以从修复XML开始,因为在您显示的示例中,您有未闭合的标记.你也可以包装< Building>标签到< Buildings>集合,以便能够在此Location类别中具有除建筑物之外的其他属性.
<?xml version="1.0" encoding="utf-8" ?> <info> <locations> <location name="New York"> <Buildings> <Building name="Building1"> <Rooms> <Room name="Room1"> <Capacity>18</Capacity> </Room> <Room name="Room2"> <Capacity>6</Capacity> </Room> </Rooms> </Building> <Building name="Building2"> <Rooms> <Room name="RoomA"> <Capacity>18</Capacity> </Room> </Rooms> </Building> </Buildings> </location> <location name="London"> <Buildings> <Building name="Building45"> <Rooms> <Room name="Room5"> <Capacity>6</Capacity> </Room> </Rooms> </Building> </Buildings> </location> </locations> </info>
修复XML后,您可以调整模型.我建议您使用属性而不是类中的字段:
public class Location { [XmlAttribute("name")] public string Name { get; set; } public List<Building> Buildings { get; set; } } public class Building { [XmlAttribute("name")] public string Name { get; set; } public List<Room> 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<Location> Locations { get; set; } }
现在剩下的就是反序列化XML:
var serializer = new XmlSerializer(typeof(Info)); using (var reader = XmlReader.Create("locations.xml")) { Info info = (Info)serializer.Deserialize(reader); List<Location> locations = info.Locations; // do whatever you wanted to do with those locations }