用LINQ解析复杂的XML

本文关键字:XML 复杂 LINQ | 更新日期: 2023-09-27 18:03:33

我生成了以下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>

这是我用来拉它的代码,但这给了我一个系统。得到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);
    }
}

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

用LINQ解析复杂的XML

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

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

应为

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

在这里,代码应该做null检查(?)如果你正在使用c# 6)来避免"对象引用异常",如果你预测如果它不总是符合模式和值