简体   繁体   English

如何绑定具有复杂对象属性的对象集合?

[英]How can I bind my collection of objects with complex object attribute?

I am trying to load XML data that consists of a collection of Employee objects. 我正在尝试加载包含Employee对象集合的XML数据。 The following function works fine for properties that are simple data types like String and Int. 以下函数适用于简单数据类型的属性,例如String和Int。 I am wondering how can I import data types of complex type. 我想知道如何导入复杂类型的数据类型。 For example, 例如,

This function works fine: 此功能正常工作:

private void LoadData()
{
   XDocument employeesDoc = XDocument.Load("Employees.xml");
   List<Employee> data = (from employee in employeesDoc.Descendants("Employee")
      select new Employee
      {
         FirstName= employee.Attribute("FirstName").Value,
         LastName = employee.Attribute("LastName ").Value,
         PhoneNumber = employee.Attribute("PhoneNumber").Value
      }).ToList();
  Employees.ItemsSource = data;
}

Here is the Employee class: 这是Employee类:

public class Employee
{
  public int Id { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }
  public string PhoneNumber { get; set; }
  public Department Department { get; set; }
}

Here is the Department class: 这是部门课程:

public class Department
{
  public int Id { get; set; }
  public string Name { get; set; }
  public string Description { get; set; }
  public Employee Manager { get; set; }
}

So, if my XML file looks like so: 因此,如果我的XML文件如下所示:

<Employees>
    <Employee FirstName="John" LastName="Summers" PhoneNumber="703-548-7841" Department="Finance"></Employee>
    <Employee FirstName="Susan" LastName="Hughey" PhoneNumber="549-461-7962" Department="HR"></Employee>

So, if the Department is a complex object and it is a string in XML file, how can I change my LoadData() function to import it into my Employee object collection? 因此,如果Department是一个复杂的对象,并且是XML文件中的字符串,那么如何更改LoadData()函数以将其导入到Employee对象集合中?

You have a couple of options, but everything depends how you get your XML (how it was saved). 您有两种选择,但是一切都取决于您如何获取XML(如何保存)。 The easiest way (to my mind) to read is: 在我看来,最简单的阅读方法是:

XmlSerializer serializer = new XmlSerializer(typeof(YourType));
using (TextReader tr = new StreamReader("newSecret.xml"))
{
 YourType rrr = (YourType)serializer.Deserialize(tr);
}

More Examples here: http://msdn.microsoft.com/en-us/library/he66c7f1.aspx 此处有更多示例: http : //msdn.microsoft.com/zh-cn/library/he66c7f1.aspx

From the other hand if you (for some reasone) should use LINQ - take a look here: LINQ to XML: creating complex anonymous type and here http://blogs.msdn.com/b/xmlteam/archive/2007/03/24/streaming-with-linq-to-xml-part-2.aspx Hope it helps! 另一方面,如果您(出于某种原因)应该使用LINQ,请在此处查看: LINQ to XML:创建复杂的匿名类型,并在此处http://blogs.msdn.com/b/xmlteam/archive/2007/03/ 24 / streaming-with-linq-to-xml-part-2.aspx希望对您有所帮助!

If you can get the list of all departments before you load the employees, you could put the departments into a Dictionary , where the key is the name of the department. 如果可以在加载员工之前获取所有部门的列表,则可以将各个部门放入“ Dictionary ,其中的键是部门名称。 You could then load the correct department for each employee: 然后,您可以为每个员工加载正确的部门:

var departmentsDict = departments.ToDictionary(d => d.Name);

XDocument employeesDoc = XDocument.Load("Employees.xml");
List<Employee> data = (from employee in employeesDoc.Descendants("Employee")
   select new Employee
   {
      FirstName= employee.Attribute("FirstName").Value,
      LastName = employee.Attribute("LastName ").Value,
      PhoneNumber = employee.Attribute("PhoneNumber").Value,
      Department = departmentsDict[employee.Attribute("Department").Value]
   }).ToList();
Employees.ItemsSource = data;

The code might need modification, depending on what you want to do if the department doesn't exist or if someone doesn't have any department specified. 如果部门不存在或某人没有指定任何部门,则可能需要修改代码,具体取决于您要执行的操作。 This code would throw an exception in both cases. 在两种情况下,此代码都会引发异常。

    using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication2
{

    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string PhoneNumber { get; set; }
        public Department Department { get; set; }
    }
    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public Employee Manager { get; set; }
    }


    internal class Program
    {
        private static void Main(string[] args)
        {
            String filepath = @"C:\\rrrr.xml";

            #region Create Test Data
            List<Employee> list = new List<Employee>();
            for (int i = 0; i < 5; i++)
            {
                list.Add(new Employee
                             {
                                 Department = new Department
                                                  {
                                                      Description = "bla bla description " + i,
                                                      Id = i,
                                                      Manager = null,
                                                      Name = "bla bla name " + i
                                                  },
                                 FirstName = "First name " + i,
                                 Id = i + i,
                                 LastName = "Last name " + i,
                                 PhoneNumber = Guid.NewGuid().ToString()
                             });
            } 
            #endregion

            #region Save XML
            XmlSerializer serializer = new XmlSerializer(typeof(List<Employee>));
            using (Stream fs = new FileStream(filepath, FileMode.Create))
            {
                using (XmlWriter writer = new XmlTextWriter(fs, Encoding.Unicode))
                {
                    serializer.Serialize(writer, list);
                }
            } 
            #endregion


            //Read from XML

            XmlDocument doc = new XmlDocument();
            doc.Load(filepath);

            List<Employee> newList = new List<Employee>();
            foreach (XmlNode node in doc.GetElementsByTagName("Employee"))
            {
                Employee ee = GetEmploee(node);
                newList.Add(ee);
            }

            //ta da
        }

        public static Employee GetEmploee(XmlNode node)
        {
            return node == null
                       ? new Employee()
                       : new Employee
                             {
                                 Department = GetDepartment(node["Department"]),
                                 FirstName = (node["FirstName"]).InnerText,
                                 LastName = (node["LastName"]).InnerText,
                                 Id = Convert.ToInt32((node["Id"]).InnerText),
                                 PhoneNumber = (node["PhoneNumber"]).InnerText
                             };
        }

        public static Department GetDepartment(XmlNode node)
        {
            return node == null
                       ? new Department()
                       : new Department
                             {
                                 Description = node["Description"].InnerText,
                                 Id = Convert.ToInt32(node["Id"].InnerText),
                                 Manager = GetEmploee(node["Manager"]),
                                 Name = node["Name"].InnerText
                             };
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何绑定到c#中的对象对象属性 - How to bind to an objects object attribute in c# 在Umbraco中,如何将对象的通用列表绑定到我的视图? - In Umbraco, how can I bind a generic list of Objects to my View? 如何将具有复杂数据对象的DataTable绑定到GridView? - How do I bind a DataTable with complex data objects to a GridView? 如何将复杂类绑定到视图,同时保留我的自定义验证属性? - how can I bind a complex class to a view, while preserving my custom validation attributes? 如何将多个对象绑定到集合? - How to bind multiple objects to a collection? 如何管理复杂对象中的基元? - How can I manage primitives in complex objects? 如何将IDictionary对象的IList绑定到数据源的集合? - How do I bind a IList of IDictionary objects to the collection of a data source? 如何在ASP.NET MVC(5)中绑定复杂对象集合属性而在表单发布中没有索引? - How to Bind a Complex Object Collection Property in ASP.NET MVC (5) without an Index in the Form Post? 如何将列表框绑定到位于ViewModel中的复杂类型内的集合? - How to bind a listbox to a collection within a complex type located within my ViewModel? 如何将复杂对象绑定到Telerik的RadGrid - How to bind complex objects to Telerik's RadGrid
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM