检查xml数据中是否存在特定节点

时间:2014-04-01 09:37:41

标签: c# linq linq-to-xml xelement

我有一个下面给出的xml数据。我需要检查生产部门中是否存在empName =“John”的员工。如果存在更新工资,否则将员工添加到部门。

 <Company>   
    <Company Name="ABCDEF" />
    <Place="AKR" />
    <Production>
       <employee empName="John" empId="E11" salary="1000" />
       <employee empName="Ivan" empId="E12" salary="3000" />
       <employee empName="Paul" empId="E13" salary="1200" />
    </Production>
    <Marketing>
      <employee empName="Keith" empId="EMP11" />
      <employee empName="Christina" empId="EMP12" />
    </Marketing>
  </Company>

我需要使用c#linq?

检查此数据中是否存在特定节点

3 个答案:

答案 0 :(得分:1)

首先纠正您的XML,

<Company>
  <Company Name="ABCDEF" />
    <Production>
    <employee empName="John" empId="E11" salary="1000" />
    <employee empName="Ivan" empId="E12" salary="3000" />
    <employee empName="Paul" empId="E13" salary="1200" />
  </Production>
  <Marketing>
    <employee empName="Keith" empId="EMP11" />
    <employee empName="Christina" empId="EMP12" />
  </Marketing>
</Company>

你可以这样尝试

    string filePaths = "XMLFile1.xml";
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(filePaths);
    XmlNodeList elements = xmlDoc.GetElementsByTagName("employee");
    Boolean found = false;
    foreach (XmlElement element in elements)
    {

        if (element.GetAttribute("empName") == "John")
        {
            found = true;
            break;
        }
    }

答案 1 :(得分:1)

您的XML无效;你不能拥有像<Place="AKR" />

这样的节点

但是,在将其更改为有效的内容后,您可以尝试使用此LINQ语句:

XDocument root = XDocument.Parse(File.ReadAllText("xml.xml"));

IEnumerable<XElement> production = root.Root
    .Descendants("Production")
    .Where(x => x.Elements("employee")
        .Where(e => e.Attribute("empName").Value.Equals("John"))
        .Any()
    );

if (production.Any())
{
    Console.WriteLine("John found...");
}
else
{
    Console.WriteLine("No John found");
}

答案 2 :(得分:0)

试试这个:

XmlNode node = xmlDoc.SelectSingleNode(NodeName);