Monday, April 26, 2010

Code4Food #5: How to get specific XML nodes using Linq to XML ?

Hi, another question has been received from Bytes.com.

So the problem was that we needed to get all the tags “Error” from a specific XML without actually caring to much about where exactly in the XML tree is Error tag. And we need to do this using Linq to Xml.

So he got an xml like these:

<Users>
      <User>
           <FirstName>Tom</FirstName>
           <LastName>Won</LastName>
           <Error>Test 2</Error>
       </User>
      <User>
           <FirstName>Jim</FirstName>
           <LastName>Kim</LastName>
           <Error>Test 2</Error>
       </User>
       <Error>Test 3</Error>
</Users>

Now this problem isn't actually a problem at all. All you need is to use Linq to XML objects like XElement, XDocument, XNode, and so on (opposite thing to XmlElement, XmlDocument, and XmlNode). Actually you can do it without directly using Linq, by callings Descendants(XName name) method.

So this is the code that I’ve written to make this done.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;

namespace GetErrorTags.Linq2Xml
{
    static class Program
    {
        static void Main()
        {
            // Load the document into root XElement.
            // Remember in Linq you work with XDocument, XElement, XNode and not with XmlDocument, etc.
            XElement rootElement = XElement.Load("ErrorTags.xml");

            // without directly using Linq
            var errorTags = rootElement.Descendants("Error");

            Console.WriteLine("==============Without using Linq=========");

            foreach (XElement tagError in errorTags)
            {
                Console.WriteLine(tagError);
            }

            Console.ReadKey();

            // using Ling directly, we'll select only "Test 2" errors
            var linqErrorTags = rootElement.Descendants("Error").Where(element => element.Value.Equals("Test 2"));

            Console.WriteLine("==============Using Linq=========");

            foreach (XElement tagError in linqErrorTags)
            {
                Console.WriteLine(tagError);
            }

            Console.ReadKey();

        }
    }
}

And here is the output:

Download source

No comments:

Post a Comment