[英]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.