Retrieve similar nodes in XML using C# Linq

This is the C# way to retrieve values from similar nodes inside a parent node.

Given input XML data

xml

    C# Code:
namespace XMLTest
{
    class Program
    {

        static void Main(string[] args)
        {
            string text = System.IO.File.ReadAllText(@"E:\testxml.txt");
            Console.WriteLine(text);

            Console.WriteLine("\n\n OUTPUT :\n");
            ReadXML(text);
        }

        public static void ReadXML(string xmlContent)
        {
            //Read the XML file
            XDocument xmlDoc = XDocument.Parse(xmlContent);
            IEnumerable xmlData_PackageNodes = xmlDoc.Descendants("linux").Descendants("package");

            for (int i = 0; i < xmlData_PackageNodes.Count(); i++)
            {
                //Get a single 'Package' node 
                XElement singleItem = xmlData_PackageNodes.ElementAt(i);

                //Get all the child 'driver' nodes with this name as IEnumerable
                IEnumerable driverNodes = singleItem.Descendants("driver");

                Console.WriteLine("=========");
                Console.WriteLine("For i = " + i);
                //get the 'driver' nodes as array
                foreach (XElement t in driverNodes)
                {
                    Console.WriteLine(t.Value.Trim());
                }

                Console.WriteLine("=========");
            }
        }
    }
}

OUTPUT:

OP

About Max
My Interests: ------------------ Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: