Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET 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
Nevron Chart
Search :       Advanced Search »
Home » XML in C# » Reading and Writing XML in C#

Reading and Writing XML in C#

In this tutorial, you will learn how to read and write XML documents in Microsoft .NET using C# language.

Author Rank :
Page Views : 1977254
Downloads : 1988
Rating :
 Rate it
Level : Intermediate
   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
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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. 

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.

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

                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;

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

            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:\\ dir
XmlTextWriter 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. 

//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';

            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
doc.Load(reader);
// Display contents on the console
doc.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");

            // write dataset contents to an xml file by calling WriteXml method

            ds.WriteXml("C:\\OutputXML.xml");

        }

    }

}


Summary

.NET Framework Library provides a good support to work with XML documents. The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.

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
 Article Extensions
Contents added by dmdv dmdv on Jun 30, 2011
Contents added by LE PHUONG on Nov 12, 2010
Download File: AnotherTetrisAI.zip
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
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:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Are you guys testing comments? by Mahesh On August 14, 2007
?
Reply | Email | Modify 
Please help me in spotting the problem in this code by hemendra On August 21, 2007
public static bool Validate(string p_strMmlFrag, out string p_strErr)
{
  p_strErr=string.Empty;
 
//starting of if statement
  if m_xsc==null)
   {
    m_xsc=new XmlSchemaCollection();
    try
     {
       string path=AppDomain.CurrentDomain.BaseDirectory+m_strSchema;
        if (!File.Exists(path))
        {
          path=AppDomain.CurrentDoamin.BaseDirectory+"/bin"+m_strSchema;
        }
        XmlTextReader xmlFile=new XmlTextReader(path);
        m_ifSchema=XmlSchema.Read(xmlFile, new ValidationEventHandler (ValidationCallBack));
 
        //Error rises in the above line as the destination file path (stored in path variable), I have just created (the file) and it's definitely empty. I tried the above mentioned solution but it's giving error!!!!!!!!
 
         m_xsc.Add(m_ifSchema);
 
// ending of if statement
 
catch
{
-----
}
-------
------
-------
------
private const string m_strSchema="StructureLinkage.xsd"
private static XmlSchemaCollection=m_xsc;
private static XmlSchema m_ifSchema;
 
// For the first time only m_xsc in null and after that it does not need to enter into above block of code once m_xsc is instantiated.
 
 
}
 
Reply | Email | Modify 
thanks mahesh by nagarakesh On October 14, 2007
hey Mahesh Thanks a lot man I was supposed to do my final nonthesis master project using XML and C# but i dont have proper good basics bz i m a starter for xml stuff Ur examples helpedme a lot Hope u will even help me out withmy future doubts regarding my project thanks once again
Reply | Email | Modify 
Please Help- Me by srikanth On October 16, 2007
Hi Sir, I want to know how can we create a xml file by using a xsd file in C#.Net.Plz send me the code . Plz send me as early as possible.I want this very urgently. Thanks, Srikanth
Reply | Email | Modify 
How do we append data to XML files? by Karthik On February 21, 2008
Can anyone tell me how to append an XML file? I am able to create an XML file but not able to append it using a StremReader as it creates multiple roots in the XML. Does anyone have a solution for this?
Reply | Email | Modify 
Thanks a lot by Hameed On March 15, 2008
U r simply the great person,because the identification of great person is that ,they share knowledge I am really thankfull as this article teach me a great deal of XML Subject Thanks & Regard Hameed
Reply | Email | Modify 
sample application by NEWMAN On August 18, 2008
Do u ve ay sample application reg this....im new to xml in c#.
Reply | Email | Modify 
sample application by NEWMAN On August 18, 2008
Do u ve ay sample application reg this....im new to xml in c#.
Reply | Email | Modify 
Re: sample application by Mahesh On February 24, 2009
I guess I did not post the code. You simply create a project and copy and paste code from this article.
Reply | Email | Modify 
How to read SVG files in C# by Marcos On September 22, 2008
Hi. I want to know how to read a SVG (Scalable Vector Graphics) in C#. I found a library called svgnet but the documentation does not explain how to read a simple svg file and how to adquire the properties. If you know or if you can help me please please explain me. Sorry about the question, I'm new in this subject. Thanks.
Reply | Email | Modify 
Thanks by Aksar On October 16, 2008
Its a Wonderful Article, Thanks!!!! It is very helpful for new in xml.
Reply | Email | Modify 
Re: Thanks by Mahesh On April 2, 2009
You're welcome. Here are more beginner articles/tutorials:
http://www.c-sharpcorner.com/Beginners/
Reply | Email | Modify 
Re: Re: Thanks by Uta On April 7, 2011
Thanks for more beginners guides 'cause I feel myself an absolute blond reading most of the advanced posts. Hope, now I'll finally manage to finish my <a href="http://www.besttermpaper.com/services/research-paper.html">research paper</a> in Info Technologies that has been my nightmare for the last couple months. Best regards, Uta.
Reply | Email | Modify 
xml reading and writing by poster On October 23, 2008
Reply | Email | Modify 
nice article but have some qry, will you plz solve it by lovely On March 2, 2009
its really very good article, I dont know anything about XML but after read this article I have learned how to create XML file, how to read data from XML file and how to use Database also. thank you for this nice article..but i have one probm? will you please solve it... whenever I create XML file its not take an relative path ,its always take absolute path...y?
Reply | Email | Modify 
Re: nice article but have some qry, will you plz solve it by Mahesh On April 2, 2009
Please post your questions on C# Corner forums.
Reply | Email | Modify 
Sequence Diagram To C# by Aysh On March 23, 2009
Could  you help me to get the code which can read the xml code that produced from UML sequence diagram by MagicDraw.
Reply | Email | Modify 
Re: Sequence Diagram To C# by Mahesh On April 2, 2009
I am not sure. Please post your questions on C# Corner forums.
Reply | Email | Modify 
Excelent Article by Mohamed On April 2, 2009
I encourage you to write books... I found this article better than reading a book. 1- the flaw of thoughts was well-structured and smooth. 2- Clear and well-defined terms. 3- Short but Comprehensive. Provide me with books you wrote, and I will be anxious to read them. Thanks alot
Reply | Email | Modify 
Re: Excelent Article by Mahesh On April 2, 2009
Thanks Mohamad.
However, writing books is very tedius and time consuming. I am working on a book Silverlight 3 but we will see how long does it take :)
Reply | Email | Modify 
Superb.... by Srikrishna On April 9, 2009
HI Mahesh, Its a superb materail ..Beautifuuly given the concepts with the programs,,,, I liked it... Thanks, M.Srikrishna Murthy
Reply | Email | Modify 
Re: Superb.... by Mahesh On April 9, 2009
Thanks. Appreciate your comments.

Reply | Email | Modify 
Cheers dude by Noel On April 16, 2009
Much appreciated.
Reply | Email | Modify 
GOOD ARTICLE by ramla On April 20, 2009
GOOD ARTICLE
Reply | Email | Modify 
READING AND WRITING IN XML WITH C# by CHANDRA On June 12, 2009
I AM VERY PLEASED AND THANKS  WITH THIS ARTICAL
Reply | Email | Modify 
Wonderful article by sunit On June 15, 2009
What a useful article. Thats what i was looking for since morning. I am new to .net as i am a java guy. but it helped me a lot.

thansk very much.. keep publishing such articles for beginners.

Sunit
Reply | Email | Modify 
good article by sunit On June 15, 2009
What a useful article. Thats what i was looking for since morning. I am new to .net as i am a java guy. but it helped me a lot.

thansk very much.. keep publishing such articles for beginners.

Sunit
Reply | Email | Modify 
Re: by Filip On July 9, 2009
Hi,

Nice article Mahesh but there is much easier way to work with Excel using C#. You should try using 3rd party components like GemBox .NET spreadsheet component. Here you can find out why it's better to work with Excel using GemBox component then Excel Automation.

Filip
Reply | Email | Modify 
Thank you!! by Lewis On September 2, 2009
thank you very much
it was a very nice way to get into XML  :)
Reply | Email | Modify 
question by xtorm On September 8, 2009
i solved the problem passing the datagrid with the info filtered to a XML File... yeah!!

heres my solution,
for(y=0....)
   for(x=0....)
      string AvaLue = mYdAtaGridView.Rows[y].Cells[x].Value.ToString();

still i have to give some xsl style to present info on a web browser,
but for now its ok.. thanks for the info mahesh.. you are awesome..
Reply | Email | Modify 
Reading XMl Spreadsheet from C# by c On November 11, 2009
Hi
I would like to read data from specific location from XML Spreadsheet file and then modify the data and revert back it to the main file. Could you gys plz help me
Reply | Email | Modify 
Great Article by udayakumar On November 28, 2009
I am new to xml. So it was very easy for getting into the xmls coz of ur article. Great Job dude... Continue posting usefull articles...
Reply | Email | Modify 
aa by gaurav On December 10, 2009
aa
Reply | Email | Modify 
XML by usman On December 12, 2009
hi sir .... i want the code of... cricket match data in an xml file and then draw a graph of that data in gdi... plz help me of this ... as soon as possible....
Reply | Email | Modify 
please help wish by azmi On December 23, 2009
Dear sir i want go to learn programming language.I am beginner i want programming smiller like that image snapshoot software and restore the system.And later Data recovery and backup software.Can you tell me if i just learn C sharp enaough for me or visual.basic orwich one is the solution.
please mail me
please i am very unhappy no body told me about that.please please help me
my mail akaleciklioglu@gmail.com
Best wisches and happy holiday
AZMI
Reply | Email | Modify 
Re: please help wish by Mahesh On December 24, 2009
I am not sure if you can just build a good software if you are a beginner. It is going to take you a lot more time to learn programming before you can start building this backup recovery software. I am not sure what manager will give such kind of work to a beginner and expect you to deliver good code on time.

Just start learning on this site. Click on Beginners link at the top to get started with some basic tutorials.
Reply | Email | Modify 
Re: Re: please help wish by thanish On January 2, 2010
hi.

<a>
<b>
<c>hi</c>
<c>hello</c>
</c>how are you</c>
</b>
</a>
how can we get all values from c tag.
can u help me plase,i ve used xmlnodelist.but dont know how to get value one by one.
thanks in advance
Reply | Email | Modify 
Thank you by kris On December 29, 2009
It's helped me alot.But this is to generate for one table but I need to generate xml files for all tables in my database.Is that possible?
Reply | Email | Modify 
asp.net 2.0 c# XmlTextReader by xxx On January 2, 2010
hi there i'm trying to iterate through the Shippers.xml file using an XmlTextReader. For each <Shipper> node, add a row to the ShippersTable containing the shipper's company name and phone number.

xml file below:
<?xml version="1.0" encoding="UTF-8"?>
<dataroot>
  <Shippers>
    <ShipperID>1</ShipperID>
    <CompanyName>Speedy Express</CompanyName>
    <Phone>(503) 555-9831</Phone>
  </Shippers>
  <Shippers>
    <ShipperID>2</ShipperID>
    <CompanyName>United Package</CompanyName>
    <Phone>(503) 555-3199</Phone>
  </Shippers>
  <Shippers>
    <ShipperID>3</ShipperID>
    <CompanyName>Federal Shipping</CompanyName>
    <Phone>(503) 555-9931</Phone>
  </Shippers>
</dataroot>

c# code below:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Xml;

namespace XMLFiles
{
    public partial class _Default : System.Web.UI.Page
    {
        string message;

        protected void Page_Load(object sender, EventArgs e)
        {
            //instantiate a XmlTextReader object with path of xml file to read.
            XmlTextReader xtReader = new XmlTextReader(Server.MapPath("~/App_Data/Shippers.xml"));
           
            //2)instantiate an XmlNodeList to get collection of nodes with specified root of those nodes
            //XmlNodeList nodeList = root.SelectNodes("//Shippers");


            //iterate through the Shippers.xml file using an XmlTextReader.
            while (xtReader.Read())
            {
                switch (xtReader.NodeType)
                {
                   
                    case XmlNodeType.Attribute:
                        break;
                    case XmlNodeType.CDATA:
                        break;
                    case XmlNodeType.Comment:
                        break;
                    case XmlNodeType.Document:
                        break;
                    case XmlNodeType.DocumentFragment:
                        break;
                    case XmlNodeType.DocumentType:
                        break;
                    // The node is an element.
                    case XmlNodeType.Element:
                        if (xtReader.Name == "Shippers")
                        {
                            Response.Write("<" + xtReader.Name + ">" + "<br />");
                            //set border style of the ShippersTable
                            ShippersTable.BorderStyle = BorderStyle.Solid;

                            //instantiate a TableRow object to add a row.
                            TableRow oTableRow = new TableRow();

                            //Create the company name column
                            TableCell oTableCell = new TableCell();

                            //set the the instantiated object cell style
                            oTableCell.BorderStyle = BorderStyle.Solid;

                            //add the XmlTextReader value to the TableCell Control
                            oTableCell.Controls.Add(new LiteralControl(xtReader.AttributeCount.ToString()));

                            //add the TableCell value to the TableCell Collection
                            oTableRow.Cells.Add(oTableCell);

                            //add the row to the ShippersTable
                            ShippersTable.Rows.Add(oTableRow);
                        }
                        break;
                    //Display the end of the element.
                    case XmlNodeType.EndElement:
                        //Response.Write("</" + xtReader.Name + ">");
                        break;
                    case XmlNodeType.EndEntity:
                        break;
                    case XmlNodeType.Entity:
                        break;
                    case XmlNodeType.EntityReference:
                        break;
                    case XmlNodeType.None:
                        break;
                    case XmlNodeType.Notation:
                        break;
                    case XmlNodeType.ProcessingInstruction:
                        break;
                    case XmlNodeType.SignificantWhitespace:
                        break;
                    //Display the text in each element.
                    case XmlNodeType.Text:
                        //Response.Write(xtReader.Value);
                        break;
                    case XmlNodeType.Whitespace:
                        break;
                    case XmlNodeType.XmlDeclaration:
                        break;
                    default:
                        break;
                }

                //For each <Shippers> node, add a row to the ShippersTable containing
                //the shipper's company name and phone number
                //foreach (XmlNode shipper in nodeList)
                //{

             
                //}
            }

        }
    }
}

Reply | Email | Modify 
Just wanted to thank you by Kaido On January 7, 2010
So ok i just started with c# and wanted to thank you cause your articles are really great for understanding how things are working. So keep it up your stuff is really good :)
Reply | Email | Modify 
XmlDocu,ent from a class by Miri On January 13, 2010

Hi
You gave examples of creating XmlDocument from string or a file (x.xml). What is the way to create a XmlDocument from a class. I used a XmlSerielization to serialize my class to file stream - a file. only after a file I could create xmlDocument. Is there a way to serialize a class to xmlDocument without creating a file first. Thank
Miri

Reply | Email | Modify 
embeded schema in xml file by Phuong On January 13, 2010

How to build xml file with embeded schema?  thanks

Reply | Email | Modify 
Help on my Scenario by Surendra babu On January 15, 2010
Hi,
This article helped me very much for my application. Thanks alot. I have some more doubt.
I have a scenario like this,
I have a list of data's displayed in a grid, say it has columns named, messagename, status etc.
For example take the message names are M1, M2, M3, M4, M5, M6.
My exact scenario is i have to select some message in the grid and if i press a Button named "Manual" XML file has to be generated for each selected message.
Suppose if i select M1, M4, M5 and i press "Manual" button i should create M1.XML, M4. XML and M5.XML in a specified folder.

Please help me as soon as possible

Thanks and regards,
Suren
Reply | Email | Modify 
Hope you can help by newbetonet On February 3, 2010
Hello, I have used this link and created a microsoft word 2007 to a back end oracle database and it does work.  I can go next or previous records but I like to be able to get a prompt that I can type i.e. last name and go to dataset and get the data.  Can you help?

http://www.codeproject.com/KB/office/Connect_Word_to_your_data.aspx


thanks very much.
Reply | Email | Modify 
Close file? by William On April 25, 2010
this is hogwash.
You have to close a file after readint it.
Reply | Email | Modify 
I need ur help by sam On April 27, 2010
Pls help me i want to store sql express table data in xml file hw do i do that by using asp.net page and c# its really urgent pls help me out il b really tthankful to u
Reply | Email | Modify 
Seeking for tip and guide to my project. by marlon On April 30, 2010
Hi Mahesh.

I found your page interesting regarding XML. I'm presently working as entry level programmer and honestly not having too much experience with c# and xml technology. I'm into a project and they asked me to make an editor window to load and update the contents of an existing XML document. Once the document load the user can then update the contents and be able to save it back the same format. I don't where to start and how. I hope you can provide me some tips and things to get a head start of this.

Thank you.

Marlon
Reply | Email | Modify 
Xml is easy now by Jo On May 3, 2010
It is intersting article, acttually I was trying to avoid working in XML for 5 years since I am mainly a C++ programmer, and I was solving all issues that need XML by databases
After I find how easy to work with XMLs I will start from now
Thank you
AutoHex
Reply | Email | Modify 
brilliant mahesh ji by kuwar On June 15, 2010
hello mahesh ji
you aree brilliant and your code gives many developers a neww way to programming
Reply | Email | Modify 
Great Article!!! by anamika On July 7, 2010
Thanks a lot for such a nice article.
Reply | Email | Modify 
XMLTextWriter and FCK Editor by ranjay On August 10, 2010
<?xml version="1.0" encoding="us-ascii"?>
<WebApplications>
  <WebApplication>
    <Date>10/08/2010 5:48:48 PM</Date>
    <Programmer>Primary Objects</Programmer>
    <Name>Hello World</Name>
    <Language>C# ASP .NET</Language>
    <Status>Complete</Status>
  </WebApplication>
</WebApplications>

And Code Here

using System.xml

 FredCK.FCKeditorV2.FCKeditor ctl00_ContentPlaceHolder1_FCKeditor1 = new FredCK.FCKeditorV2.FCKeditor();
        string strFCK = FCKeditor1.Value.ToString().Trim();
        string strFile = Server.MapPath("xmlNews.xml");
        // Create an XML document. Write our specific values into the document.
        XmlTextWriter xmlWriter = new XmlTextWriter(strFile, System.Text.Encoding.ASCII);
        xmlWriter.Formatting = Formatting.Indented;
        // Write the XML document header.
        xmlWriter.WriteStartDocument();

        // Write our first XML header.
        xmlWriter.WriteStartElement("WebApplications");

        // Write an element representing a single web application object.
        xmlWriter.WriteStartElement("WebApplication");

        // Write child element data for our web application object.
        xmlWriter.WriteElementString("Date", DateTime.Now.ToString());
        xmlWriter.WriteElementString("Programmer", "Primary Objects");
        xmlWriter.WriteElementString("Name", "Hello World");
        xmlWriter.WriteElementString("Language", "C# ASP .NET");
        xmlWriter.WriteElementString("Status", "Complete");

        // End the element WebApplication
        xmlWriter.WriteEndElement();

        // End the document WebApplications
        xmlWriter.WriteEndElement();

        // Finilize the XML document by writing any required closing tag.
        xmlWriter.WriteEndDocument();
        xmlWriter.Flush();
        xmlWriter.Close();
Reply | Email | Modify 
Good article. Thanks. by Chitranjan On August 25, 2010
Good article. Thanks.
Reply | Email | Modify 
Lame by Blake On October 11, 2010
Too bad there isn't any example xml files so I could follow this without starting a new project.
Reply | Email | Modify 
Thanks for your efforts by Amit On October 14, 2010
This is really helpful, really appreciate your efforts to post such a useful information.

Thanks,
Amit
Reply | Email | Modify 
hello by bougie On October 18, 2010


hi mahesh,
I need to ask a question what I'm trying to develop is:
I need to send a querto the data base using Xml and the data base send me back the resulted data and I need to view it in data grid view...
how can I do such thing...
thank you for your article.

Reply | Email | Modify 
Re: hello by Mahesh On November 7, 2010
Yes. You can even save direct XML in the database and read and write back and forth. DataSet object is nothing but XML.
Reply | Email | Modify 
Thanks by asdas On January 30, 2011
This is beautiful. Thank you. I will follow this in my application
Reply | Email | Modify 
WPF by Venkatgiri On February 9, 2011
How to use richtextbox in wpf?
Reply | Email | Modify 
WPF by Venkatgiri On February 9, 2011
How to implement richtextbox in WPF in c# and save and load the file in xml without changing any font style and get the data...
Reply | Email | Modify 
Good Article !! by naveen On February 27, 2011
Hi Mahesh, Thanks for a great article .. I'm newbie in using XML classes in .Net and your article helped me a lot,but currently i am facing a situation where i need to store XML in to SQL DB tables using ADO.Net , it would be helpfull if you can throw some samples on how to store XML to database. Thanks in Advance Naveen
Reply | Email | Modify 
How to Read XML File and Insert into SQL Table in Windows service by bennnyraja On March 1, 2011
Pls help me........ How to Read XML File and Insert into SQL Table in Windows service......
Reply | Email | Modify 
Thanks a lot....... by Teena On March 23, 2011
Hi sir, I am a beginner in s/w field and this article really helped me a lot in learning xml in C#.
Reply | Email | Modify 
C# by Nidheesh On March 29, 2011
how to create inotifypropertychanged class in C#
Reply | Email | Modify 
good xml example by Crish On March 29, 2011
good article for XML reading, writing etc
Reply | Email | Modify 
great basic article by peleg On October 21, 2011
but if you have put some much work, why not to write more cleaner and correct code, for example : 1)using case 2)using operator overloading, ex: ac = ac + 1; ==> ++ac;
Reply | Email | Modify 
Re: great basic article by Mahesh On November 23, 2011
Good point peleg. Keep in mind, this article was written 10 years ago. I wasn't that experienced and didnt have many features.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.