Friday, February 26, 2010

Reading a xml file-Basics

Introduction

The main reason for writing this simple article is so many guys are asking doubts how to read Xml ,how to Write Xml in DotnetSpider Questions section. I Thought this article Will helpful for beginners. You can also find an article about how to write Xml document at
http://www.dotnetspider.com/kb/SubmitSample.aspx?ArticleId=2066

System.Xml namespace contains the XmlReader and XmlTextReader.
The XmlTextReader class is derived from XmlReader class. The XmlTextReader class can be used to read the XML documents. The read function of this document reads the document until end of its nodes.
Using the XmlTextReader class you get a forward only stream of XML data j It is then possible to handle each element as you read it without holding the entire DOM in memory.
XmlTextReader provides direct parsing and tokenizing of XML and implements the XML 1.0 specifications

This article explains how to read an Xml file.

Adding NameSpace as Reference

The first step in the process of reading Xml file is to add System.Xml namespace as reference to our project ,since System.Xml namespace contains the XmlReader and XmlTextReader.




using System.Xml;



let us assume there is an Xml file in c:\Dir\XmlExample.Xml

Open an Xml Document

Create an instance of an XmlTextReader object, and populate it with the XML file. Typically, the XmlTextReader class is used if you need to access the XML as raw data without the overhead of a DOM; thus, the XmlTextReader class provides a faster mechanism for reading XML.




XmlTextReader MyReader = new XmlTextReader("c:\\dir\\XmlExample.Xml");



the above code opens Xml file

Reading Data

The Read method of the XmlTextReader class read the data. See the code



while (MyReader.Read())
{
Response.Write(MyReader.Name);
}



that’s all now we are ready to read our Xml file from the above specified directory


Read the XML File into DataSet


You can use the ReadXml method to read XML schema and data into a DataSet. XML data can be read directly from a file, a Stream object, an XmlWriter object, or a TextWriter object.

The code simply looks like the following



string MyXmlFile = @"c:\\Dir\\XmlExample2.xml";
DataSet ds = new DataSet();

System.IO.FileStream MyReadXml = new System.IO.FileStream(MyXmlFile,System.IO.FileMode.Open);
ds.ReadXml(MyReadXml);

DataGrid1.DataSource = ds;
DataGrid1.DataBind();




Thus we can read Xml Data into Dataset .

No comments:

Post a Comment

Followers