我試圖從XML文件中取出特定的員工ID,以便查找員工關聯的某些組,然後將這些組作爲元素添加到XML中。如何使用Linq to XML獲取XML屬性值?
首先,我需要employeeId,然後我可以查找一些信息,但我不瞭解如何獲取它。我猜我沒有得到它,因爲所有的嵌套節點。
這裏是XML結構。
<CXIXML>
<Directives>
<Updates>
<Emp tasEmpID="00123" lName="Doe" fName="John" empStatus="A" city="HDQ" />
<Emp tasEmpID="00456" lName="Smith" fName="Jane" empStatus="A" city="HDQ" />
</Updates>
</Directives>
</CXIXML>
這是我試過但我沒有得到的ID。
private static void SetGroupAssociations(string xmlFile)
{
XElement xelement = XElement.Load(xmlFile);
IEnumerable<XElement> employees = xelement.Elements();
foreach (var employee in employees)
{
var employeeId = from e in employee.Descendants("Emp")
select new
{
Id = e.Element("tasEmpID")
};
Console.WriteLine(employeeId);
}
}
最終我需要最終得到類似下面的內容。因此,關於如何在特定員工節點之後添加新元素的任何建議都會很好,但首先我至少要讓員工查看他們的團隊。
<CXIXML>
<Directives>
<Updates>
<Emp tasEmpID="00123" lName="Doe" fName="John" empStatus="A" city="HDQ" />
<Group groupId="1">
<Group groupId="5">
<Group groupId="12">
<Emp tasEmpID="00456" lName="Smith" fName="Jane" empStatus="A" city="HDQ" />
<Group groupId="1">
</Updates>
</Directives>
</CXIXML>
您是否發佈了相關的xml數據?你的C#代碼嘗試從「sharpID」元素中獲取值,但是在你的XML中沒有這樣的屬性。 –
已編輯。有幾個屬性具有相同的值。我修剪了一些屬性以減少發佈的代碼。 – Caverman
看看我寫給你的答案。 –