Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » Visual C# » XML with C-sharp

XML with C-sharp

Through this article you will learn how to handle XML in c#.

Page Views : 75286
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

 

In this article you will see how to read and write XML documents in Microsoft.NET using C# language. First I will discuss XML.NET Framework Library namespace and classes in brief. Then we will read and write XML documents. At the end of this article, I will show you how to take advantage of ADO.NET and XML.NET model to read and write XML documents from relational databases and vice versa.

 

Introduction to Microsoft .NET XML Namespaces and Classes

Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library.

 

.NET provides five namespace to support XML classes. These are as follows:

 

  • System.Xml
  • System.Xml.Schema
  • System.Xml.Serialization
  • System.Xml.XPath
  • System.Xml.Xsl

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. These classes are as follows:

 

  • XmlReader
  • XmlTextReader
  • XmlValidatingReader
  • XmlNodeReader
  • XmlWriter
  • XmlTextWriter

As you can see there are four reader and two writer classes. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents.

 

The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are as follows:

 

  • MoveToAttribute
  • MoveToFirstAttribute
  • MoveToContent
  • MoveToFirstContent
  • MoveToElement
  • MoveToNextAttribute

ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example. 

 

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.

 

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example. 

 

Reading XML Documents

In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line:

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

Or you can use any XML file. 

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor. 

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber and so on.

 

Example

using System;

using System.Collections.Generic;

using System.Text;

using System.Collections;

using System.IO;

using System.Xml;

using System.Xml.Serialization;

 

namespace XMLSerialzation

{

    class Program

    {

        static void Main(string[] args)

        {

            ShoppingList myList = new ShoppingList();

            myList.AddItem(new Item("eggs",1.49));

            myList.AddItem(new Item("ground beef", 3.69));

            myList.AddItem(new Item("bread",0.89));

            Console.WriteLine("in main after adding ");

            // Serialization

            XmlSerializer s = new XmlSerializer(typeof(ShoppingList));

            Console.WriteLine("xml serializer object created ");

            TextWriter w = new StreamWriter(@"c:\list.xml");

            Console.WriteLine("text writer serializer object created ");

            s.Serialize(w, myList);

            Console.WriteLine("serialize called ");

            w.Close();

 

            // Deserialization

            ShoppingList newList;

            TextReader r = new StreamReader(@"c:\list.xml");

            newList = (ShoppingList)s.Deserialize(r);

            r.Close();

            Console.ReadLine();

        }

    }

 

    [XmlRoot("shoppingList")]

    public class ShoppingList

    {

        private ArrayList listShopping;

 

        public ShoppingList()

        {

            listShopping = new ArrayList();

        }

 

        [XmlElement("itemone")]

        public Item[] Items

        {

            get

            {

                Item[] items = new Item[listShopping.Count];

                listShopping.CopyTo(items);

                Console.WriteLine("called get  of item []");

                return items;

            }

            set

            {

                if (value == null) return;

                Item[] items = (Item[])value;

                listShopping.Clear();

                foreach (Item item in items)

                listShopping.Add(item);

            }

        }

     

         public int AddItem(Item item)

        {

            Console.WriteLine("in AddItem with item object ");

            Console.WriteLine("return "+listShopping.Add(item));

            return listShopping.Add(item);

        }

    }

 

    // Items in the shopping list

    public class Item

    {

        [XmlAttribute("name")]

        public string name;

        [XmlAttribute("price")]

        public double price;

 

        public Item()

        {

        }

 

        public Item(string Name, double Price)

        {

            Console.WriteLine("in item constructor with two argument");

            name = Name;

            price = Price;

        }

    }

}

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Praveen Jain
Praveen jain is a java developer having more than 1 year of experience in developing web application, messaging using JMS, also interested in c# and now implementing messaging in c# using Activemq NMS.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Re: by Filip On July 16, 2009
Hi,

nice article but there is much more simple way to work with Excel in C#. Try using 3rd party components. For example you can try GemBox Excel .NET component. It has free version which you can use to see if component is useful to you.

Here is a list of reason why it's better to use GemBox spreadsheet component then Excel Interop

Filip
GemBox.Spreadsheet for .NET - Easily read and write Excel (XLS, XLSX or CSV) files or export to HTML files from your .NET apps.
Reply | Email | Modify 
a small mistake... by danny On August 12, 2009
very interesting article, it was quite helpful to me when learnning XML serialization.
I did find a small mistake though, you add every item twice, in the method:

public int AddItem(Item item)

        {

            Console.WriteLine("in AddItem with item object ");

            Console.WriteLine("return "+listShopping.Add(item));

            return listShopping.Add(item);

        }


notice how "listShopping.Add(item)" appears twice,

the solution would be to change the line " return listShopping.Add(item); "

into " return listShopping.Count; "


thanks again.


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

Danny, Los Angeles Locksmith


Reply | Email | Modify 
Good by yelkal On January 13, 2010

Good but how can i creat class for scxml (statchart xml) expression or fremwork in modelview control ye_mu79@yahoo.com.  i think i will get fast response with example

Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.