27
Using XML in C# in the simplest way By irfan patel | 14 Jul 2004 The sheer power of C# and its ease with XML is displayed here. With zero knowledge, you can just jump into this article and end up learning XML upto the intermediate level. Download demo project - 18.1 Kb Introduction Like HTML, XML is made for the World Wide Web but the set of tags are not fixed. They can be extended and hence the name. We can have our own tags. The only thing we have to do is to maintain a structural relationship between them. It's written in SGML (Standard Generalized Markup Language) which is an international standard for defining descriptions across the globe. XML was developed way back in 1996 by an XML Working Group (known originally as the SGML Editorial Review Board) which was formed under the guidance of the World Wide Web Consortium (W3C) which was chaired by Jon Bosak of Sun Microsystems. But, B-U-T, but many of us in spite of being in IT, still do not know much about XML. Like my previous article, even this one assumes the reader to be a beginner (or intermediate) to help you know even some hidden facts. Getting late!! Let's get back to work first!! To start with, just follow the instructions step by step. Thanks in advance for your co-operation. :) Step By Step Walkthrough 1. Goto File->New->Blank Solution. 2. Select Visual C# Projects in Project Types.

11579_xml in c sharp

Embed Size (px)

Citation preview

Page 1: 11579_xml in c sharp

Using XML in C# in the simplest wayBy irfan patel | 14 Jul 2004 The sheer power of C# and its ease with XML is displayed here. With zero knowledge, you can just jump into this article and end up learning XML upto the intermediate level.

Download demo project - 18.1 Kb

Introduction

Like HTML, XML is made for the World Wide Web but the set of tags are not fixed. They can be extended and hence the name. We can have our own tags. The only thing we have to do is to maintain a structural relationship between them. It's written in SGML (Standard Generalized Markup Language) which is an international standard for defining descriptions across the globe.

XML was developed way back in 1996 by an XML Working Group (known originally as the SGML Editorial Review Board) which was formed under the guidance of the World Wide Web Consortium (W3C) which was chaired by Jon Bosak of Sun Microsystems. But, B-U-T, but many of us in spite of being in IT, still do not know much about XML. Like my previous article, even this one assumes the reader to be a beginner (or intermediate) to help you know even some hidden facts.

Getting late!! Let's get back to work first!!

To start with, just follow the instructions step by step. Thanks in advance for your co-operation. :)

Step By Step Walkthrough

1. Goto File->New->Blank Solution. 2. Select Visual C# Projects in Project Types.

3. Select WindowsApplication in Templates.

Page 2: 11579_xml in c sharp

4. Type for eg., XMLReadWrite in the Name textbox.

Creating an XML file (the data file which will be read by our application)

Note: You will be demonstrated in Visual Studio .NET but you can create an XML file in literally any text editor.

1. Go to menu Project->Add New Item. 2. In the dialog box select XMLFile and click Open.

Note:- It is generally recommended to give an appropriate name wherever required but please follow the instructions as it is, for simplicity.

3. Locate the following line.

Collapse | Copy Code

<?xml version="1.0" encoding="utf-8" ?>

4. Below the line, add the following XML piece.

Collapse | Copy Code

<Book>

<BookName>C# Professional</BookName>

<BookName>C# Cookbook</BookName>

<BookName>SQL Server Black Book</BookName>

<BookName>Mastering VB.Net</BookName>

<BookName>ASP.Net Unleashed</BookName>

<BookName>.Net Framework Essentials</BookName>

<ReleaseYear>2001</ReleaseYear>

<ReleaseYear>2002</ReleaseYear>

<ReleaseYear>2003</ReleaseYear>

<ReleaseYear>2004</ReleaseYear>

<Publication>EEE</Publication>

<Publication>Microsoft Press</Publication>

<Publication>O 'Reilly</Publication>

<Publication>BpB</Publication>

<Publication>Sams TechMedia</Publication>

</Book>

Creating the schema (.XSD) file for validating our just made .xml file)

1. Go to menu XML -> Create Schema.

Page 3: 11579_xml in c sharp

2. Notice that in the solution explorer, it has created a file XMLFile1.xsd.

3. Also notice what the IDE (Integrated Development Environment) has added in <Book> tag of ours.

4. It signifies our .xml file will be validated against which Schema file.

Creating a class clsSValidator

1. In the solution explorer, right click the XMLReadWrite project name. 2. Go to Add-> New Folder and name the folder as Classes.

3. Now right click the Classes folder name in the solution explorer.

4. Go to Add-> Add New Item.

5. Select class and name it as clsSValidator.cls.

6. This class needs the following namespaces. So paste it on top of the class.

Collapse | Copy Code

using System;

using System.Xml;

using System.Xml.Schema;

using System.Windows.Forms;

7. Just above the constructor, declare the following variables:

Collapse | Copy Code

// variable declarations

private string m_sXMLFileName ;

private string m_sSchemaFileName ;

private XmlSchemaCollection m_objXmlSchemaCollection ;

private bool m_bIsFailure=false ;

8. Below the constructor clsSValidator, paste the following:

Collapse | Copy Code

//We are overloading the constructor

//The following code creates a XmlSchemaCollection object

//this objects takes the xml file's Schema and adds it to its collection

public clsSValidator (string sXMLFileName, string sSchemaFileName)

{

Page 4: 11579_xml in c sharp

m_sXMLFileName = sXMLFileName;

m_sSchemaFileName = sSchemaFileName;

m_objXmlSchemaCollection = new XmlSchemaCollection ();

//adding the schema file to the newly created schema collection

m_objXmlSchemaCollection.Add (null, m_sSchemaFileName);

}

9. Just below the above code, add the following function:

Collapse | Copy Code

//This function will Validate the XML file(.xml) against xml schema(.xsd)

public bool ValidateXMLFile()

{

XmlTextReader objXmlTextReader =null;

XmlValidatingReader objXmlValidatingReader=null ;

try

{

//creating a text reader for the XML file already picked by the

//overloaded constructor above viz..clsSchemaValidator

objXmlTextReader = new XmlTextReader(m_sXMLFileName);

//creating a validating reader for that objXmlTextReader just created

objXmlValidatingReader = new XmlValidatingReader (objXmlTextReader);

//For validation we are adding the schema collection in

//ValidatingReaders Schema collection.

objXmlValidatingReader.Schemas.Add (m_objXmlSchemaCollection);

//Attaching the event handler now in case of failures

objXmlValidatingReader.ValidationEventHandler +=

new ValidationEventHandler

(ValidationFailed);

//Actually validating the data in the XML file with a empty while.

//which would fire the event ValidationEventHandler and invoke

//our ValidationFailed function

while (objXmlValidatingReader.Read())

{

}

//Note:- If any issue is faced in the above while it will invoke

//ValidationFailed which will in turn set the module level

//m_bIsFailure boolean variable to false thus returning true as

//a signal to the calling function that the ValidateXMLFile

//function(this function) has encountered failure

return m_bIsFailure;

}

Page 5: 11579_xml in c sharp

catch (Exception ex)

{

MessageBox.Show ("Exception : " + ex.Message);

return true;

}

finally

{

// close the readers, no matter what.

objXmlValidatingReader.Close ();

objXmlTextReader.Close ();

}

}

10. Notice that we are using an event handler in the ValidateXML function above.

11. Add the following snippet right below it:

Collapse | Copy Code

private void ValidationFailed (object sender, ValidationEventArgs args)

{

m_bIsFailure = true;

MessageBox.Show ("Invalid XML File: " + args.Message);

}

//This will be called only if an the XML file is not in proper format.

//Since it is a file like HTML any one can go and change its format from

//any text editor. So we shud ensure that we are validating it properly.

Reading the values from the XML file

1. Right click Form1 in Solution Explorer and select View Code. 2. Replace the namespaces used on the top by the following snippet:

Collapse | Copy Code

using System;

using System.Windows.Forms;

using System.Xml;

using XMLReadWrite.Classes;

3. Right click Form1 in Solution Explorer and select View Designer. 4. From the toolbox, place three labels, three comboboxes and one command button as

shown in the figure.

5. Change their properties as following:

Page 6: 11579_xml in c sharp

Name Property Value

Label1 Caption Book Name

Label2 Caption Release Year

Label3 Caption Publication

Combo1 (Name) cboBookName

  Text [make it blank]

DropDownStyle DropDownList

Combo2 (Name) cboReleaseYear

Text [make it blank]

DropDownStyle DropDownList

Combo3 (Name) cboPublication

Text [make it blank]

  DropDownStyle DropDownList

Button1  (Name) cmdWriteToFile

  Text &Write To File

6. Double click on the form (not on any other controls area) to open its Load event.

Note: XmlTextReader (Namespace:- System.Xml) is used in our code below. It

gives a read-only forward only access. This class helps us to read XML from stream or file with a very important feature of skipping unwanted data from it. Check out our usage below:

7. Just above the Load event paste the following code:

Collapse | Copy Code

private void ReadXMLFileAndFillCombos()

{

try

{

string sStartupPath = Application.StartupPath;

clsSValidator objclsSValidator =

new clsSValidator(sStartupPath + @"..\..\..\XMLFile1.xml",

sStartupPath + @"..\..\..\XMLFile1.xsd");

if (objclsSValidator.ValidateXMLFile()) return;

XmlTextReader objXmlTextReader =

new XmlTextReader(sStartupPath + @"..\..\..\XMLFile1.xml");

Page 7: 11579_xml in c sharp

string sName="";

while ( objXmlTextReader.Read() )

{

switch (objXmlTextReader.NodeType)

{

case XmlNodeType.Element:

sName=objXmlTextReader.Name;

break;

case XmlNodeType.Text:

switch(sName)

{

case "BookName":

cboBookName.Items.Add(objXmlTextReader.Value);

break;

case "ReleaseYear":

cboReleaseYear.Items.Add(objXmlTextReader.Value);

break;

case "Publication":

cboPublication.Items.Add(objXmlTextReader.Value);

break;

}

break;

}

}

}

catch(Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

8. Now in the load event paste the following to call this method:

Collapse | Copy Code

ReadXMLFileAndFillCombos();

Writing the values to the XML file

1. Now right click the form1 again in solution explorer and go to its designer. 2. Double click the command button to see its Click event.

Page 8: 11579_xml in c sharp

Note: XmlTextWriter (Namespace: System.Xml) is used in our code below. This

class helps us to write XML on many places like stream, console, file etc. We are pushing the XML on a file. Simply nest the Start and End method and it's done.

3. Just above the click event paste the following snippet:

Collapse | Copy Code

private void WriteXMLFileUsingValuesFromCombos()

{

try

{

string sStartupPath = Application.StartupPath;

XmlTextWriter objXmlTextWriter =

new XmlTextWriter(sStartupPath + @"\selected.xml",null);

objXmlTextWriter.Formatting = Formatting.Indented;

objXmlTextWriter.WriteStartDocument();

objXmlTextWriter.WriteStartElement("MySelectedValues");

objXmlTextWriter.WriteStartElement("BookName");

objXmlTextWriter.WriteString(cboBookName.Text);

objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteStartElement("ReleaseYear");

objXmlTextWriter.WriteString(cboReleaseYear.Text);

objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteStartElement("Publication");

objXmlTextWriter.WriteString(cboPublication.Text);

objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteEndElement();

objXmlTextWriter.WriteEndDocument();

objXmlTextWriter.Flush();

objXmlTextWriter.Close();

MessageBox.Show("The following file has been successfully created\r\n"

+ sStartupPath

+ @"\selected.xml","XML",MessageBoxButtons.OK,

MessageBoxIcon.Information );

}

catch(Exception ex)

{

MessageBox.Show(ex.ToString());

}

}

4. Now we have to call this method from the click event of the button. So make it look like the following:

Page 9: 11579_xml in c sharp

Collapse | Copy Code

private void cmdWriteToFile_Click(object sender, System.EventArgs e)

{

WriteXMLFileUsingValuesFromCombos();

}

5. Run it to see its beauty ;)

Njoi programming!!

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

Page 10: 11579_xml in c sharp

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

Page 11: 11579_xml in c sharp

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

Page 12: 11579_xml in c sharp

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

30.5.2.Create XmlReader from Stream

using System;using System.Collections.Generic;using System.Text;using System.Net;using System.Xml;using System.IO;

class MainClass{    static void Main(string[] args)    {        WebClient client = new WebClient();

Page 13: 11579_xml in c sharp

        Stream rssFeedStream = client.OpenRead("http://yourRssFeedURL");

        XmlReader reader = XmlReader.Create(rssFeedStream);

        reader.MoveToContent();

        while (reader.ReadToFollowing("item"))        {            ProcessItem(reader.ReadSubtree());        }    }

    static void ProcessItem(XmlReader reader)    {        reader.ReadToFollowing("title");        string title = reader.ReadElementContentAsString("title", reader.NamespaceURI);

        reader.ReadToFollowing("link");        string link = reader.ReadElementContentAsString("link", reader.NamespaceURI);        Console.WriteLine("{0}\n\t{1}", title, link);    }}

30.5.6.Read Xml output from database

using System;using System.Collections.Generic;using System.ComponentModel;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Data;using System.Data.SqlClient;using System.Xml;using System.IO;using System.Diagnostics;

    public class MainClass    {        public static void Main()        {            SqlConnection cnn = new SqlConnection(@"data source=.\sqlexpress;initial catalog=northwind;integrated            SqlCommand cmd = new SqlCommand();            cmd.Connection = cnn;            cmd.CommandType = CommandType.Text;            cmd.CommandText = "select * from Employee FOR XML AUTO";            cnn.Open();            XmlReader reader=cmd.ExecuteXmlReader();            StreamWriter writer= File.CreateText(Application.StartupPath + @"\temp.xml");            writer.Write("<root>");            while (reader.Read())

Page 14: 11579_xml in c sharp

            {                writer.Write(reader.ReadOuterXml());            }            writer.Write("</root>");            writer.Close();            reader.Close();            cnn.Close();            Process.Start(Application.StartupPath + @"\temp.xml");        }    }

30.5.7.Chaining an XmlReader to an XmlWriter

using System;using System.Xml; using System.IO;using System.Text;public class Test2{  static string ipKey;  static string httpMethodKey;  static string fileKey;   static string dateKey;  static string referrerKey; 

  public static void WriteAttributes(XmlReader reader, XmlWriter writer){        if(reader.MoveToFirstAttribute()){      do{        writer.WriteAttributeString(reader.Prefix,                 reader.LocalName,                 reader.NamespaceURI,                reader.Value);       }while(reader.MoveToNextAttribute());      reader.MoveToElement();     }  }

  public static void WriteEvent(XmlWriter writer, string ip){        writer.WriteStartElement("event");     writer.WriteElementString("ip", ip);    writer.WriteEndElement();   } 

  public static void ReadEvent(XmlReader reader, out string ip){

    ip = null; 

    while( reader.Read() && reader.NodeType != XmlNodeType.EndElement){                       if (reader.NodeType == XmlNodeType.Element) {               if(reader.Name == ipKey){          ip = reader.ReadString();      }

Page 15: 11579_xml in c sharp

    }//while     }  }  public static void Main(string[] args){    string ip;     XmlNameTable xnt = new NameTable();     ipKey            = xnt.Add("ip");         //load XmlTextReader using XmlNameTable above     XmlTextReader xr = new XmlTextReader("logfile.xml", xnt);    xr.WhitespaceHandling = WhitespaceHandling.Significant;

    XmlValidatingReader vr = new XmlValidatingReader(xr);    vr.ValidationType = ValidationType.None;    vr.EntityHandling = EntityHandling.ExpandEntities; 

    StreamWriter sw =  new StreamWriter ("logfile-archive.xml", false, Encoding.UTF8 );     XmlWriter xw    = new XmlTextWriter (sw);                         vr.MoveToContent();    xw.WriteStartElement(vr.Prefix, vr.LocalName, vr.NamespaceURI);    WriteAttributes(vr, xw);             vr.Read();     do    {      ReadEvent(vr, out ip);      WriteEvent(xw,ip);       vr.Read();     } while(vr.NodeType == XmlNodeType.Element);            vr.Close();    xw.Close();  }}

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. Then, you will see how to read and write XML documents. In 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 - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes. 

Page 16: 11579_xml in c sharp

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. 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. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes. 

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 MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and  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. 

The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.

In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList. 

Next namespace in Xml series is System.Xml.Schema. It classes  to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType. 

The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams. 

The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes  -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document. 

The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.

Page 17: 11579_xml in c sharp

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 an so on.

List 1 reads a document and displays a node information using these properties. 

About Sample Example 1

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output. 

Sample Example 1.

using System;using System.Xml;namespace ReadXml1{ class Class1 { static void Main(string[] args) { // Create an isntance of XmlTextReader and call Read method to read the file XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); textReader.Read(); // If the node has value while (textReader.Read()) { // Move to fist element textReader.MoveToElement(); Console.WriteLine("XmlTextReader Properties Test"); Console.WriteLine("==================="); // Read this element's properties and display them on console Console.WriteLine("Name:" + textReader.Name); Console.WriteLine("Base URI:" + textReader.BaseURI); Console.WriteLine("Local Name:" + textReader.LocalName);

Page 18: 11579_xml in c sharp

Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString()); Console.WriteLine("Depth:" + textReader.Depth.ToString()); Console.WriteLine("Line Number:" + textReader.LineNumber.ToString()); Console.WriteLine("Node Type:" + textReader.NodeType.ToString()); Console.WriteLine("Attribute Count:" + textReader.Value.ToString()); } } }}

 

The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.

List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has. 

About Sample Example 2

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.

Sample Example 2.

using System;using System.Xml;namespace ReadingXML2{ class Class1 { static void Main(string[] args) { int ws = 0; int pi = 0; int dc = 0; int cc = 0; int ac = 0; int et = 0; int el = 0; int xd = 0; // Read a document XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); // Read until end of file while (textReader.Read()) { XmlNodeType nType = textReader.NodeType;

Page 19: 11579_xml in c sharp

// If node type us a declaration if (nType == XmlNodeType.XmlDeclaration) { Console.WriteLine("Declaration:" + textReader.Name.ToString()); xd = xd + 1; } // if node type is a comment if (nType == XmlNodeType.Comment) { Console.WriteLine("Comment:" + textReader.Name.ToString()); cc = cc + 1; } // if node type us an attribute if (nType == XmlNodeType.Attribute) { Console.WriteLine("Attribute:" + textReader.Name.ToString()); ac = ac + 1; } // if node type is an element if (nType == XmlNodeType.Element) { Console.WriteLine("Element:" + textReader.Name.ToString()); el = el + 1; } // if node type is an entity\ if (nType == XmlNodeType.Entity) { Console.WriteLine("Entity:" + textReader.Name.ToString()); et = et + 1; } // if node type is a Process Instruction if (nType == XmlNodeType.Entity) { Console.WriteLine("Entity:" + textReader.Name.ToString()); pi = pi + 1; } // if node type a document if (nType == XmlNodeType.DocumentType) { Console.WriteLine("Document:" + textReader.Name.ToString()); dc = dc + 1; } // if node type is white space if (nType == XmlNodeType.Whitespace) { Console.WriteLine("WhiteSpace:" + textReader.Name.ToString()); ws = ws + 1; } } // Write the summary Console.WriteLine("Total Comments:" + cc.ToString());

Page 20: 11579_xml in c sharp

Console.WriteLine("Total Attributes:" + ac.ToString()); Console.WriteLine("Total Elements:" + el.ToString()); Console.WriteLine("Total Entity:" + et.ToString()); Console.WriteLine("Total Process Instructions:" + pi.ToString()); Console.WriteLine("Total Declaration:" + xd.ToString()); Console.WriteLine("Total DocumentType:" + dc.ToString()); Console.WriteLine("Total WhiteSpaces:" + ws.ToString()); } }}

Writing XML Documents

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.              

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class. 

Although, it's not possible to describe all the Writexxx methods here, let's see some of them.

First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.

In my sample example, I create a file myXmlFile.xml in C:\\ root directory. 

// Create a new file in C:\\ dirXmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;

After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.

textWriter.WriteStartDocument(); textWriter.WriteEndDocument(); textWriter.Close();  

The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it.  WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.

WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document. 

Page 21: 11579_xml in c sharp

//Write the ProcessingInstruction node string PI= "type='text/xsl' href='book.xsl'" textWriter.WriteProcessingInstruction("xml-stylesheet", PI); //'Write the DocumentType node textWriter.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'softcover'>");

The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter: 

After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.

About Sample Example 3 

In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items. 

Sample Example 3.

using System;using System.Xml;namespace ReadingXML2{ class Class1 { static void Main(string[] args) { // Create a new file in C:\\ dir XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null); // Opens the document textWriter.WriteStartDocument(); // Write comments textWriter.WriteComment("First Comment XmlTextWriter Sample Example"); textWriter.WriteComment("myXmlFile.xml in root dir"); // Write first element textWriter.WriteStartElement("Student"); textWriter.WriteStartElement("r", "RECORD", "urn:record"); // Write next element textWriter.WriteStartElement("Name", ""); textWriter.WriteString("Student"); textWriter.WriteEndElement(); // Write one more element textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony"); textWriter.WriteEndElement(); // WriteChars char[] ch = new char[3]; ch[0] = 'a'; ch[1] = 'r'; ch[2] = 'c';

Page 22: 11579_xml in c sharp

textWriter.WriteStartElement("Char"); textWriter.WriteChars(ch, 0, ch.Length); textWriter.WriteEndElement(); // Ends the document. textWriter.WriteEndDocument(); // close writer textWriter.Close(); } }}

 

Using XmlDocument

The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article. 

Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.

About Sample Example 4

This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file. 

Sample Example 4.

//Create the XmlDocument.XmlDocument doc = new XmlDocument();doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy ex</Name></Student>")); //Save the document to a file.doc.Save("C:\\std.xml"); You can also use Save method to display contents on console if you pass Console.Out as a arameter. For example: doc.Save(Console.Out);

About Sample Example 5 

Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console

Sample Example 5.

XmlDocument doc = new XmlDocument();//Load the the document with the last book node.XmlTextReader reader = new XmlTextReader("c:\\books.xml");reader.Read(); // load reader

Page 23: 11579_xml in c sharp

doc.Load(reader);// Display contents on the consoledoc.Save(Console.Out);

Writing Data from a database to an XML Document

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document. 

The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.  

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query. 

About Sample Example 6 

 In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter. 

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir. 

Sample Example 6. 

using System;using System.Xml;using System.Data;using System.Data.OleDb; namespace ReadingXML2{ class Class1 { static void Main(string[] args) { // create a connection OleDbConnection con = new OleDbConnection(); con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb"; // create a data adapter OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con); // create a new dataset DataSet ds = new DataSet(); // fill dataset da.Fill(ds, "Customers");

Page 24: 11579_xml in c sharp

// write dataset contents to an xml file by calling WriteXml method ds.WriteXml("C:\\OutputXML.xml"); } }}