Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » XML .NET » XML with C-sharp

XML with C-sharp

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

Total page views :  45072
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Powerful ASP.NET Hosting w/ NO Setup Fees. Click Here!
Become a Sponsor


Download Free Book

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;

        }

    }

}


Login to add your contents and source code to 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.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
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.
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
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 | Delete | 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 | Delete | 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 | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 1999 - 2010  Mindcracker LLC. All Rights Reserved