将绑定xml绑定到Model Class

我正在尝试使用xml作为小型CMS的数据库,如图库或员工档案等

然而,所有亚音的头脑我坚持我如何将我的xml文档绑定到一个模型类,以便我可以使用该类进行强类型视图:

这是我的模型类:

[XmlRoot("employee")] public class EmployeesModel { [Required] [DisplayName("Name: ")] [XmlElement("employeeName")] public string employeeName { get; set; } [Required] [DisplayName("Position: ")] [XmlElement("employeePosition")] public string employeePosition { get; set; } [Required] [DisplayName("Description")] [XmlElement("employeeDescription")] public string employeeDescription { get; set; } [Required] [DisplayName("Photo: ")] [XmlElement("employeePhoto")] public string employeePhoto { get; set; } [Required] [DisplayName("ID: ")] [XmlElement("employeeID")] public int employeeID { get; set; } } 

这是我的代码:

 XDocument xmlDoc = XDocument.Load(Server.MapPath("~/App_Data/employees.xml")); var model = (from xml in xmlDoc.Descendants("employee") select xml) as IEnumerable; return View(model); 

XML

    David parker Senior Web Developer This is a test description
feele free to add something here. mypic.jpg 1

xml方面工作,但模型总是空的,但是我在尝试绑定时没有得到运行时错误,我知道我应该做的更多,但我需要一些帮助。

为清楚起见,我使用的是asp.net mvc 2 rc 2

谢谢

您需要将XML 反序列化为对象。 您不能简单地将XML转换为对象。 当你说as IEnumerable ,你会得到一个null因为类型不兼容。 您的代码可能如下所示:

 var serializer = new XmlSerializer(typeof(EmployeesModel)); var model = from xml in xmlDoc.Descendants("employee") select serializer.Deserialize(xml.CreateReader()) as EmployeesModel; 

您可以考虑的另一个选项是将XElement 投影到EmployeesModel对象中,如下所示:

 var model = from xml in xmlDoc.Descendants("employee") select new EmployeesModel { employeeName = (string)xml.Element("employeeName"), employeePosition = (string)xml.Element("employeePosition"), employeeDescription = (string)xml.Element("employeeDescription"), employeePhoto = (string)xml.Element("employeePhoto"), employeeID = (int)xml.Element("employeeID"), }; 

如你所见,这可能会变得单调乏味。 但是,它可能是适当的。 如果您的XML文件表示所有员工数据,但您的视图仅显示数据的子集或不同结构中的数据,则您可能不希望视图模型直接复制数据存储的内容。

如果要将make xml绑定到模型类,可以在codeplex上使用templay。 此外,您可以在模型类及其子类上执行某些操作。

https://templay.codeplex.com/