0

I have an xml data given below. I need to check whether an employee of empName="John" exists in Production department. If exists update the salary otherwise add an employee to the department.

 <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>

I need to check particular node exist in this data using c# linq?

Sudha
  • 2,078
  • 6
  • 28
  • 53

3 Answers3

1

Correct your XML first,

<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>

you can try like this

    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;
        }
    }
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

Your XML is invalid; you cannot have a node like <Place="AKR" />

But, after changing it into something valid, you could try using this LINQ statement:

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");
}
Reinder Wit
  • 6,490
  • 1
  • 25
  • 36
0

try this:

XmlNode node = xmlDoc.SelectSingleNode(NodeName);
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
omriman12
  • 1,644
  • 7
  • 25
  • 48