0

I have an XElement which contains similar nodes but different values. Like my XElement look like this

<Information>
    <Emp>
        <A.EMPLID>1</A.EMPLID>
        <A.Phone>12##</A.Phone>
    </Emp>
    <Emp_Add>
        <B.ID>125</B.ID>
        <Add>XXXXXXX</Add>
    </Emp_Add>
    <Emp_Add>
        <B.ID>1256</B.ID>
        <Add>ZZZZZZ</Add>
    </Emp_Add>
</Information>

Actually I need to go through each <Emp_Add> node - pick up the value of <B.ID> and compare it with <Emp>.<A.EMPLID> value. If values are same then display message "Values matched" else message "Values does not match" using C# code.

How to use for each loop and compare for such XElement.

ernesthm
  • 421
  • 4
  • 15
user2897967
  • 337
  • 2
  • 8
  • 24
  • Can you vote and/or comment if my answer was util for you? – ernesthm May 09 '18 at 20:31
  • It's time to read this excellent book [Pro LINQ in C# 2010](https://www.apress.com/us/book/9781430226536) to be more familiar with LINQ to XML. – JohnyL May 09 '18 at 20:39

1 Answers1

0

I think you need something like this

See my dotnetfiddle.

var xml =
                "<Information>\r\n\t<Emp>\r\n\t\t<A.EMPLID>1</A.EMPLID>\r\n\t\t<A.Phone>12##</A.Phone>\r\n\t</Emp>\r\n\t<Emp_Add>\r\n\t\t<B.ID>125</B.ID>\r\n\t\t<Add>XXXXXXX</Add>\r\n\t</Emp_Add>\r\n\t<Emp_Add>\r\n\t\t<B.ID>1256</B.ID>\r\n\t\t<Add>ZZZZZZ</Add>\r\n\t</Emp_Add>\r\n</Information>";
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);
        XDocument xmlObj = XDocument.Parse(xmlDoc.OuterXml);

        var emplId = xmlObj.Descendants().Descendants().Descendants().FirstOrDefault().Value;
        var empsAdd = xmlObj.Descendants().Descendants().Where(d => d.Name.LocalName == "Emp_Add");
        foreach (var emp in empsAdd)
        {
            var currentEmpIdNode = emp.Descendants().FirstOrDefault();
            Console.WriteLine(currentEmpIdNode != null && currentEmpIdNode.Value == emplId
                              ? "Values matched"
                              : "Values does not match");
        }
ernesthm
  • 421
  • 4
  • 15