读取XML中特定属性的最佳方法

时间:2013-05-15 14:22:54

标签: c# .net xml xml-parsing

我正在尝试在自定义对象中读取此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;}
}

提前致谢。

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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);


        }