0

我正在尝试在我的自定义对象中读取此 xml 文件并需要一些帮助。最后,我想为每条记录创建员工列表。

<Records>
  <Record>
     <Item NAME="EMPLOYEE NAME">
        <IValue>Henry</IValue>
     </Item>
     <Item NAME="EMPLOYEE ID">
        <IValue>321</IValue>
     <Item>         
  </Record>
      ..More Record 
<Records>

员工等级:

public class Employee
{
    public string EmployeeName {get;set;}
    public string EmployeeId {get;set;}
}

提前致谢。

4

2 回答 2

1
var employees = XDocument.Parse(xmlstring) //XDocument.Load(filename)
                    .Descendants("Record")
                    .Select(r => new Employee
                    {
                        EmployeeId = r.Elements("Item")
                                      .First(e => e.Attribute("NAME").Value == "EMPLOYEE ID").Value,
                        EmployeeName = r.Elements("Item")
                                       .First(e => e.Attribute("NAME").Value == "EMPLOYEE NAME").Value,
                    })
                    .ToList();
于 2013-05-15T14:54:58.610 回答
0

关于什么

// Open the xml file and create the element list
XDocument doc = XDocument.Load("C://data.xml");
var ElementList = doc.Root.Elements();

// Crate the Employee list and populate
List<Employee> list = new List<Employee>();
foreach (XElement item in listaElementi)
{
   list.Add(new Employee { EmployeeName = item.Descendants().First().Value, EmployeeId = item.Descendants().Last().Value });
}

Descendant().First() 和 Descendant().Last() 取决于 xml 的结构。通过这种方式,您将在内存中加载您的 xml。

如果您要从 xml 中读取多个字段,我可以提出以下解决方案

  // You need a dictionary to map the columns of the data into the property of the
  //class since they have different names.

  Dictionary<string, string> dictionary = new Dictionary<string, string>();
  dictionary.Add("EMPLOYEE NAME", "EmployeeName");
  dictionary.Add("EMPLOYEE ID", "EmployeeId");

  XDocument doc = XDocument.Load("C://data.xml");
  var ElementList = doc.Root.Elements();

  List<Employee> list = new List<Employee>();
  foreach (XElement item in listaElementi)
      {
         // We read the properties from the xml
         var properties = item.Descendants().Where(p => p.HasAttributes);
            Employee employee = new Employee();
         // Using reflection and the dictionary we set the property value
         foreach (var property in properties)
            {
                var t = property.FirstAttribute.Value;
                var s = property.Value;
                employee.GetType().GetProperty(dictionary[t]).SetValue(employee,s);
            }
         list.Add(employee);


        }
于 2013-05-15T14:49:48.050 回答