Link to home
Start Free TrialLog in
Avatar of Abirami Rajendran
Abirami RajendranFlag for United States of America

asked on

XML Linq C#

Hello,

See below xml. Is it possible in linq to check if "errorCode" node exist under transactionItems-transaction if so get the errorcode and message?

Thanks
<root>
<header>
...
</header>
<transactionItems>
<transaction>
<id>123</id>
<name></name>
<errorCode>3456</errorCode>
<errorMessage>invalid id</errorMessage>
</transaction>
</transactionItems>
</root>

Open in new window

Avatar of kaufmed
kaufmed
Flag of United States of America image

How about this:
using System;
using System.Linq;
using System.Xml.Linq;

namespace _27398886
{
    class Program
    {
        static void Main(string[] args)
        {
            var errorData = from trans in XDocument.Load("input.xml").Descendants("transaction")
                            where trans.Elements("errorCode").FirstOrDefault() != null
                            select new
                            {
                                ErrorCode = trans.Element("errorCode").Value,
                                ErrorMesg = trans.Element("errorMessage").Value
                            };

            foreach (var err in errorData)
            {
                Console.WriteLine("{0}: {1}", err.ErrorCode, err.ErrorMesg);
            }

            Console.ReadKey();
        }
    }
}

Open in new window

Avatar of Abirami Rajendran

ASKER

Thanks the code works perfectly.

But if there is a xml namespace for the nodes <transactionItems xmlns="..."> & <transaction xmlns="..">  then it doesnt seem to work. Any idea?
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks!
NP. Glad to help  = )