将此XML文档转换为我的对象的最简单方法是什么?
我有一个XMLDocument,我需要读入并转换为一组对象。 我有以下对象
public class Location { public string Name; public List Buildings; } public class Building { public string Name; public List Rooms; }
我有以下XML文件:
18 6 18 6
这样做的最佳方式是什么? 我应该自动将xmldocument序列化到对象还是我需要解析每个元素并手动转换为我的对象? 特别是,我试图弄清楚如何转换集合(位置,建筑物等)。
将此XML文件转换为基本的最佳建议是什么?
List
对象?
您可以从修复XML开始,因为在您显示的示例中,您有未闭合的标记。 您还可以将
标记包装到
集合中,以便能够在此Location类中具有除建筑物之外的其他属性。
18 6 18 6
修复XML后,您可以调整模型。 我建议你使用属性而不是类中的字段:
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; } }
现在剩下的就是反序列化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 }
只需使用XML序列化属性 – 例如:
public class Location { [XmlAttribute("name"); public string Name; public List Buildings; } public class Building { [XmlAttribute("name"); public string Name; public List Rooms; }
请记住 – 默认情况下,所有内容都将序列化为XML元素 – 与对象的名称相同:)
这样做加载:
using(var stream = File.OpenRead("somefile.xml")) { var serializer = new XmlSerializer(typeof(List)); var locations = (List )serializer.Deserialize(stream ); }