XML with C#

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.

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;
        }
    }
}


Similar Articles