Saturday, January 18, 2014

XML Parsing C#



XML Parsing C#:
Here is the good working example for XML Parsing in C#.

using System;
using System.Collections.Generic;
using System.Xml;

namespace org.doublecloud
{
    class XmlParsingDemo
    {
        static void Main(string[] args)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"c:\users\ilyas\documents\books.xml"); //give path;

            XmlNodeList nodes =   doc.DocumentElement.SelectNodes("/catalog/book");

            List<Book> books = new List<Book>();

            foreach (XmlNode node in nodes)
            {
                Book book = new Book();

                book.author = node.SelectSingleNode("author").InnerText;
                book.title = node.SelectSingleNode("title").InnerText;
                book.id = node.Attributes["id"].Value;

                books.Add(book);
            }

            System.Console.WriteLine("Total books: " + books.Count);
        }
    }

    class Book
    {
        public string id;
        public string title;
        public string author;
    }
}

The following is a sample XML for running the code. The content has duplications but is still good for trying out the above program.
<?xml version="1.0"?>
<catalog>
  <book id="123">
    <author>Ilyas</author>
    <title>ilyasdotnetdeveloper.blogspot.in</title>
    <genre>Computer</genre>
    <price>59.99</price>
    <publish_date>2014-09-01</publish_date>
    <description>
      An understanding stuff shared in the blog address shown.
    </description>
  </book>
  <book id="124">
    <author>Steve Jin</author>
    <title>TBD</title>
    <genre>Computer</genre>
    <price>59.99</price>
    <publish_date>2015-09-01</publish_date>
    <description>
      An in-depth introduction on something.
    </description>
</catalog>

No comments: