我有我已經生成以下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元素上做了什麼錯誤。從主管一切端接是可選的(又名它可能會或可能不會出現在一個特定的分配
* *它是否給你例外?你有沒有試過把它縮小到一個更小的例子? (刪除XML元素和相應的轉換,直到找出導致問題的元素爲止......) –
爲什麼不使用XML(De)序列化? –
它是一個簡單的錯字。 'Separation_Reason'!='SeparationReason' – Crowcoder