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

Dalibor GasicPosted May 30, 2012, 10:15 AM
I used LINQ's XElement to build XDocument. I've found it interesting and compact way to make xml documents.
Mahesh ChandPosted May 30, 2012, 10:10 AM
You could do both ways. I believe XmlNode can be used to change first node as well. But I like the way you did it. You could also use the XmlDocument class. There are several ways to do the same thing.
Dalibor GasicPosted May 30, 2012, 10:03 AM
I've solved my problem with xmldoc.Declaration = new XDeclaration("1.0", "ISO-8859-1", "true"); It is a first line of xml document, can you change contents also using XmlNode? Thanks for the book.
Mahesh ChandPosted May 30, 2012, 9:54 AM
You can find a particular node using XmlNode class and replace its contents. Here is a complete free book I wrote on XAML. Search for Find and Replace nodes: http://www.c-sharpcorner.com/ebooks/free/51/programming-xml-with-C-Sharp.aspx
Dalibor GasicPosted May 30, 2012, 8:50 AM
How to change title of xml document, like encoding? I would like to save xml with encoding = ISO-8859-1 --- <?xml version="1.0" encoding="utf-8"?> --- Tnx, Dalibor