2016-08-23 89 views
0

我有我已經生成以下XML:解析複雜的XML使用LINQ

<?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元素上做了什麼錯誤。從主管一切端接是可選的(又名它可能會或可能不會出現在一個特定的分配

+0

* *它是否給你例外?你有沒有試過把它縮小到一個更小的例子? (刪除XML元素和相應的轉換,直到找出導致問題的元素爲止......) –

+0

爲什麼不使用XML(De)序列化? –

+0

它是一個簡單的錯字。 'Separation_Reason'!='SeparationReason' – Crowcoder

回答

1

基於提供下面的代碼的XML示例:

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

應該是

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

如果您預計它不總是符合架構和值,代碼應該執行空檢查(如果您使用的是c#6),以避免出現「對象引用異常」,這是毫無價值的

+0

感謝您的幫助。它通常是小事 –

+0

另外,我一直在嘗試三重檢查,但他們一直沒有與Linq –