Search This Blog

Sunday, May 23, 2010

Parsing an XML file using C#

Link to the Code (VS 2008)


I will show you here two pieces of code in C# that will let you parse the Products.XML into a List object.
The first one makes use of the System.XML namespace, while the second use System.XML.Linq one.
The Linq code is pretty amazing, it is so simple I will not even comment it. I managed also to include a "where" clause to filter the output.

An additional note has to be done for the XMLReader methods class for the first example

xmlIn.ReadToDescendant("Product") == true  //This code move the cursor to the first "Product"


product.Code = xmlIn["Code"]; //Since we are already on the Product Element we can read its attribute with  the indexer

 xmlIn.ReadStartElement("Product"); // Checks that we are on Product Element and moves one raw ahead

product.Description = xmlIn.ReadElementContentAsString(); //Read the Content of the Element Description, and moves one raw ahead

product.Price = xmlIn.ReadElementContentAsDouble(); //Read the Content ofthe Element Price, and moves one raw ahead

xmlIn.ReadToNextSibling("Product") // Move the Cursor to the next product and return true if found

//Read The First Root Node
            if (xmlIn.ReadToDescendant("Product") == true) 
            {
                do
                {
                    Product product = new Product();
                    product.Code = xmlIn["Code"];
                    xmlIn.ReadStartElement("Product");
                    product.Description = xmlIn.ReadElementContentAsString();
                    product.Price = xmlIn.ReadElementContentAsDouble();
                    products.Add(product);
                } while (xmlIn.ReadToNextSibling("Product"));
            }











"Products.XML"
--------------------------------------------------------------------------------------------------


--------------------------------------------------------------------------------------------------

"Product.cs"
 --------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WindowsFormsApplication1
{
    class Product
    {
        public string Code { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
    }
}
 --------------------------------------------------------------------------------------------------



 Form1.cs
 --------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Create the list
            List products = new List();

            //Create the path
            string path = @"..\..\Products.xml";

            //XmlReader Settings
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            //XmlReader Objcet
            XmlReader xmlIn = XmlReader.Create(path, settings);

            //Read The First Root Node
            if (xmlIn.ReadToDescendant("Product") == true)
            {
                do
                {
                    Product product = new Product();
                    product.Code = xmlIn["Code"];
                    xmlIn.ReadStartElement("Product");
                    product.Description = xmlIn.ReadElementContentAsString();
                    product.Price = xmlIn.ReadElementContentAsDouble();
                    products.Add(product);
                } while (xmlIn.ReadToNextSibling("Product"));
            }

            xmlIn.Close();


        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Create the path
            string path = @"..\..\Products.xml";
           
            //Create the xmlDoc object
            XDocument xmlDoc = XDocument.Load(path);

            List products = (
                                from product in xmlDoc.Descendants("Product")
                                where product.Attribute("Code").Value == "A4CS"
                                select new Product
                                {
                                    Code = product.Attribute("Code").Value,
                                    Description = product.Element("Description").Value,
                                    Price = Convert.ToDouble(product.Element("Price").Value),
                                }
                           ).ToList();


            foreach (Product product in products)
            {
                Console.WriteLine(product.Code);
                Console.WriteLine(product.Description);
                Console.WriteLine(product.Price);
            }
                          
              

        }
    }
}

--------------------------------------------------------------------------------------------------

No comments:

Post a Comment