使用LINQ解析复杂的XML

时间:2016-08-23 15:54:56

标签: c# xml linq

我有以下生成的XML:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee>
    <First_Name>John</First_Name>
    <Last_Name>Doe</Last_Name>
    <TSR>12345</TSR>
    <Assignments>
      <Assignment>
        <Division>California</Division>
        <Project>Sales</Project>
        <Title>Agent</Title>
        <Start_Date PartTime="False">6/13/2012</Start_Date>
        <Supervisor>Jack Moore</Supervisor>
        <Trainer></Trainer>
        <End_Date TrainingNoShow="False">3/1/2016</End_Date>
        <Separation_Reason>Job was not a fit</Separation_Reason>
        <Termination>True</Termination>
        <Comments>
August 2, 2016: </Comments>
      </Assignment>
    </Assignments>
  </Employee>
</Employees>

这是我用来拉它的代码,但这给了我一个System.NullReferenceException:

private void ImportXMLFile(string p_strFileName) {
    XDocument xEmployees = XDocument.Load(p_strFileName);
    var employees = from employee in xEmployees.Descendants("Employee")
        select new AnEmployee 
    {  //on this line
        FirstName = employee.Element("First_Name").Value,
        LastName = employee.Element("Last_Name").Value,
        EmpID = employee.Element("TSR").Value,
        History = new List<AnAssignment>(from assignment in employee.Descendants("Assignment")
                                         select new AnAssignment
                                         {
                                            Division = assignment.Element("Division").Value,
                                            Project = assignment.Element("Project").Value,
                                            Title = assignment.Element("Title").Value,
                                            StartDate = DateTime.Parse(assignment.Element("Start_Date").Value),
                                            isPartTime = bool.Parse(assignment.Element("Start_Date").Attribute("PartTime").Value),
                                            EndDate = DateTime.Parse(assignment.Element("End_Date").Value),
                                            Supervisor = assignment.Element("Supervisor").Value,
                                            Separation = assignment.Element("SeparationReason").Value,
                                            isTerminated = bool.Parse(assignment.Element("Termination").Value),
                                            Comments = assignment.Element("Comments").Value

                                         })
    };
    foreach(AnEmployee e in employees) {
        EmployeeCollection.add(e);
    }
}

似乎没有关于Employee元素的任何内容,所以我想知道我在Assignment Element上做错了什么。从主管到终止的所有内容都是可选的(也就是说它可能会或可能不会出现在特定的任务中。

1 个答案:

答案 0 :(得分:1)

基于Xml示例提供以下代码:

 Separation = assignment.Element("SeparationReason").Value

应该是

 Separation = assignment.Element("Separation_Reason").Value

在这里,代码应该进行空检查(?。如果你使用的是c#6)以避免&#34;对象引用异常&#34;如果您预计它是否始终符合架构和值