[英]How to get an XML attribute value with Linq to XML?
我試圖從XML文件中僅獲取特定的員工ID,以便可以查找與該員工關聯的某些組,然后將這些組作為元素添加到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>
看起來與您已有的相似。 然后,在foreach中,您可以在過程中添加句子。
var document = XDocument.Load(xmlFile);
var employees = document.Descendants("Emp");
foreach (var employee in employees)
{
var employeeId = employee.Attribute("tasEmpID").Value;
Console.WriteLine(employeeId);
}
我將文檔放在一個單獨的變量中,以便您可以使用此對象保存所做的更改。
我猜您的xml結構不正確,您描述的組將在每個Emp內,所以我將假設這一點。
要通過屬性獲取員工,您可以執行以下操作:
XElement xelement = XElement.Load(xmlFile);
var emp=xelement.Descendants("Emp")
.FirstOrDefault(e=>(string)e.Attribute("tasEmpID")=="00456");
現在要將組添加到當前雇員,只需使用Add
方法:
emp.Add(groups.Select(g=>new XElement("Group",new XAttribute("groupId",g.Id))));
假設groups
變量是IEnumerable<Group>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.