LINQ to XML-避免重复条目

本文关键字:to XML- LINQ | 更新日期: 2023-09-27 18:27:38

XML结构:

<Emp>
<Employee username="John"/>      
<Employee username="Jason"/>
</Emp>

我不想通过以下linq到xml查询将重复的属性插入到xml文件中

   var newEmployee= XElement.Parse(defaultEmployee.ToString());
   var q = from p in doc.Descendants("Employee")
                        let attr = p.Attribute("username")
                        where attr != null && attr.Value != txtusername.Text 
                        select p;

     foreach(var dupes in q)
      {
         newEmployee.Attribute("username").Value = txtusername.Text ;
         doc.root.Add(newEmployee);
         doc.save(EmployeeFile);
      }

我正试图添加一个没有重复项的新员工,但我的代码仍然添加重复项。

有人能看看我的查询,告诉我哪里缺少逻辑吗?

LINQ to XML-避免重复条目

要在xml中添加新员工,不需要循环,也不需要解析任何默认的xml,只需:

doc.Root.Add(new XElement("Employee", 
                          new XAttribute("username", txtusername.Text));

我不清楚你的循环是用来做什么的,目前你正在选择任何具有不同用户名的员工,而对于每个,你都添加了一个新员工节点——这没有多大意义,我怀疑你只想添加一次新员工。

如果你想在另一方面检查具有给定用户名的员工是否已经存在:

bool userExistsAlready = doc.Descendants("Employee")
                            .Any(x=> (string)x.Attribute("username") ==  txtusername.Text);

现在,您可以对添加新员工的代码进行检查:

if(!userExistsAlready)
{
  //add new user
}

使用此LINQ查询,您可以循环用户名属性,提供DISTINCT操作:

    var q = (from p in newEmployee.Descendants("Employee").Attributes("username")
            select (string)p).Distinct();