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. Then, you will see how to 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 models to read and write XML documents from relational databases and vice versa.
Microsoft .NET XML Namespaces and Classes
Before starting to work with XML documents 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 the reader and writing class. These reader and writer classes are used to read and write XML documents. These classes are -
- XmlReader
- XmlTextReader
- XmlValidatingReader
- XmlNodeReader
- XmlWriter
- XmlTextWriter
As you can see, there are four reader and two writer classes.
The XmlReader class is an abstract bases class 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 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 called Skip to skip the current node and move to the 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, nodes, and schemas.
The XmlWrite class contains functionality to write data to XML documents. This class provides many writing methods to write XML document items. This class is the base class for the XmlTextWriter class, which we'll be using in our sample example.
The XmlNode class plays an important role. However, this class represents a single node of XML 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 the above-discussed classes, the System.Xml namespace contains more classes. A few of them are XmlConvert, XmlLinkedNode, and XmlNodeList.
The next namespace in the Xml series is System.Xml.Schema. It classes to work with XML schemas such as XmlSchema, XmlSchemaAll, XmlSchemaXPath, and XmlSchemaType.
The System.Xml.The serialization namespace contains classes that are used to serialize objects into XML format documents or streams.
The System.Xml.XPath Namespace contains XPath-related classes to use XPath specifications. This namespace has the following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation through 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.
How to read 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 the XmlTextReader class to read an XML file. You read a file by passing the file name as a parameter in the constructor.
XmlTextReader textReader = new XmlTextReader("C:\\books.xml");
After creating an instance of XmlTextReader, you call the Read method to start reading the document. After the 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.
List 1 reads a document and displays node information using these properties.
Example 1
In this sample example, I read an XML file using XmlTextReader and called the Read method to read its nodes one by one until the end of the file and display the contents to the console output.
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.
Example 2
In this sample example, I read an XML file using XmlTextReader and called the Read method to read its nodes one by one until the end of the file. After reading a node, I check its NodeType property to find the node write node contents to the console, and keep track of a number of particular types of nodes. In the end, I display the total number of different types of nodes in the document.
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.ProcessingInstruction)
{
myXMLRichTextBox.AppendText("Process Instruction:" + textReader.Name.ToString() + Environment.NewLine); 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());
}
}
}
How to Write 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 methods 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 and 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.
The 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 the 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 starting to write to it. The writeComment method writes a comment to a document. It takes only one string type of argument. The 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 that writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write 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 Write methods. After that, we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.
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.
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();
}
}
}
How to use 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 documents from a specified string. Another useful method of this class is Save. Using the Save method, you can write XML data to a string, stream, TextWriter, or XMLWriter.
Example 4
This tiny sample example is pretty easy to understand. We call the LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file.
//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 the Save method to display contents on the console if you pass the Console.Out as a parameter. For example:
doc.Save(Console.Out);
Example 5
Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read the 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 the Save method to save the document. Passing Console.Out as a Save method argument displays data on the console
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 a method to read a relational database table and write this table to an XML file. You use the WriteXml method to write a dataset data to an XML file.
In this sample example, I have used the commonly used Northwind database that comes with Office 2000 and later versions. You can use any database you want. The only thing you need to do is just chapter the connection string and SELECT SQ L query.
Example 6
In this sample, I create a data adapter object and select all records of the Customers table. After that, I can use the method to fill a dataset from the data adapter.
In this sample example, I have used OldDb data provides. You need to add a reference to the System.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 the 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 the Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and writes 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.
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 good support to work with XML documents. The XmlReader, XmlWriter, and their derived classes contain methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read the entire document. The Load and Save method of XmlDocument loads a reader or a file and saves documents respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.
Download Free Book
I have published a free book on XML programming using C#. Get your free copy here. Free e-book: Programming XML with C#
Learn more XML Programming
Still hungry for more XML programming with C# and .NET? Here is a dedicated section with hundreds of articles and code samples on XML programming using C# and .NET. XML Programming in C#
Cheers!

Tomasz JablonskiPosted Feb 1, 2023, 11:45 PM
CzlonkowieZespolu.Sort((x, y) => x.DataWstapienia.CompareTo(y.DataWstapienia));
Tomasz JablonskiPosted Feb 1, 2023, 11:45 PM
Public bool Equals(Osoba? other) { if(Pesel == other.Pesel) { return true; } else { return false; } }
Tomasz JablonskiPosted Feb 1, 2023, 11:45 PM
Public int CompareTo(CzlonekZespolu? other) { int cmpnazw = Nazwisko.CompareTo(other.Nazwisko); if (cmpnazw != 0) { return cmpnazw; } return Imie.CompareTo(other.Imie); }
Tomasz JablonskiPosted Feb 1, 2023, 11:44 PM
Public Zespol DeepCopy() { Zespol zespol = Clone() as Zespol; zespol.kierownikZespolu = kierownikZespolu.Clone() as KierownikZespolu; zespol.czlonkowieZespolu = new(); czlonkowieZespolu.ForEach(cz => zespol.czlonkowieZespolu.Add(cz.Clone() as CzlonekZespolu)); return zespol; }
Tomasz JablonskiPosted Feb 1, 2023, 11:43 PM
Regex.IsMatch(value, @"^\d{6}$") String.Format("{0:###-###-###}", Convert.ToInt32(numerTelefonu)) data.ToString("dd-MMM-yyyy") Regex.IsMatch(value, @"^[A-Z]{1}[a-z]*$")
Tomasz JablonskiPosted Feb 1, 2023, 11:42 PM
Public void ZapiszXml(string nazwa) { Klasa klasa = new Klasa(); XmlSerializer sr = new XmlSerializer(typeof(Klasa)); StreamWriter sw = new StreamWriter(nazwa); sr.Serialize(sw, klasa); } Odczyt z XML-a public static Klasa OdczytXml(string nazwa) { XmlSerializer serializer = new XmlSerializer(typeof(Klasa)); using (StreamReader reader = new StreamReader(nazwa)) { Klasa klasa = (Klasa)serializer.Deserialize(reader); return klasa; } } Zapis do postaci binarnej public void ZapiszBin(string nazwa) { BinaryFormatter formatter = new BinaryFormatter(); using (FileStream stream = new FileStream(nazwa, FileMode.Create)) { Klasa z1 = new Klasa(); formatter.Serialize(stream, z1); } } Odczyt z postaci binarnej public static Klasa OdczytBin(string nazwa) { BinaryFormatter formatter = new BinaryFormatter(); using (FileStream stream = new FileStream(nazwa, FileMode.Open)) { Klasa klasa = (Klasa)formatter.Deserialize(stream); return klasa; } } Zapis i odczyt (Postac binarna) uzywanie FileStream public void ZapiszBin(string fname) { using FileStream fs = new(fname, FileMode.Create); BinaryFormatter bf = new(); bf.Serialize(fs,this); } public static Zespol OdczytZespolu(string fname) { if(!File.Exists(fname)) { return null; } using FileStream fs = new(fname, FileMode.Open); BinaryFormatter bf = new(); return bf.Deserialize(fs) as Zespol; }
Harun OconnellPosted Jan 31, 2023, 8:38 PM
Public static void SaveXML(string name, Class c) { XmlSerializer serializer = new XmlSerializer(typeof(Class)); TextWriter writer = new StreamWriter($"{name}.xml"); serializer.Serialize(writer, c); writer.Close(); } public static Class ReadXML(string name) { XmlSerializer serializer = new XmlSerializer(typeof(Class)); FileStream fs = new FileStream($"{name}.xml", FileMode.Open); return (Class)serializer.Deserialize(fs); }
Jaroslaw KrolikowskiPosted Jun 29, 2022, 1:37 PM
There is a small mistake in the Sample Example 2 lines 44 and 46 and the code there should be as follows: if (nType == XmlNodeType.ProcessingInstruction) { myXMLRichTextBox.AppendText("Process Instruction:" + textReader.Name.ToString() + Environment.NewLine); pi = pi + 1; }
Viknaraj ManogararajahPosted Jul 22, 2018, 1:55 AM
Nice article, thank you for sharing
Willie sunPosted May 22, 2018, 4:03 AM
Test this code, the textReader.Read() give out exception, don't know why?
Willie sunPosted May 22, 2018, 4:01 AM
Test this code, the textReader1.Read() give out exception, don't know why?
Satish Kumar VadlavalliPosted Feb 22, 2018, 2:01 AM
Great and useful. one
Ganesh MotekarPosted Jul 3, 2017, 1:02 AM
Hi .. I am working on reading and writing file from drive e:g (D:/xyz/xyx.dat) file concepts , everything is working fine in local system i mean on local IIS but when i deploy my application on Server that time its getting store into server's hard drive means (Server's D:/xyz/xyx.dat) .. how to get out of this any suggestion would be highly appreciable.
Shashank MaikhuriPosted Mar 13, 2017, 1:43 AM
How to add whitespace and indents while writing xml file
reddy prasadPosted Jan 16, 2017, 1:27 AM
Good one.but i need to read an xml file and write it into another xml file using writer element
Khayinso KasarPosted Sep 8, 2016, 7:11 AM
Great article
Ramesh PalaniappanPosted Aug 18, 2016, 8:10 AM
Good One
Shobana JPosted Jul 8, 2016, 4:03 AM
Niceone
kalu singh raoPosted Jul 7, 2016, 8:37 AM
Nice...
Karthik ElumalaiPosted Jul 4, 2016, 12:16 AM
Great and useful. one
Davronbek UmirovPosted Jun 28, 2016, 7:12 AM
Usefull one..
Bhuvanesh MohankumarPosted Apr 19, 2016, 2:30 PM
Good one
Paul FleischerPosted Apr 5, 2016, 8:20 PM
I need help. I want to use xml to generate report. I don't have crystal report. I will be grateful for this help.
Keerthi VenkatesanPosted Apr 1, 2016, 9:11 AM
great
Sumi ArianiPosted Apr 1, 2016, 3:27 AM
thanks mate
Abdul BasithPosted Mar 31, 2016, 6:41 AM
great work
Vignesh ManiPosted Mar 21, 2016, 5:07 PM
Nice
Kashif SohailPosted Mar 13, 2016, 11:02 AM
Nice Article Sir
Prashant VermaPosted Mar 10, 2016, 3:13 AM
Good one
Prashant VermaPosted Mar 10, 2016, 3:13 AM
Nice article
Sirisha KPosted Mar 4, 2016, 9:57 AM
Useone
Ammar ShaukatPosted Mar 2, 2016, 12:07 PM
Good
Anil JhaPosted Mar 2, 2016, 4:33 AM
Well explained
Sonu ChaudharyPosted Feb 25, 2016, 6:28 AM
great one
Jithil JohnPosted Feb 16, 2016, 2:07 AM
Great
Shailesh UkePosted Feb 16, 2016, 1:52 AM
Nice Article
Sr KarthigaPosted Feb 10, 2016, 9:13 AM
Good one sir its very intresting
Abhay ShankerPosted Feb 6, 2016, 12:36 PM
Nice One.
Irfan AcPosted Jan 25, 2016, 1:15 AM
thanks
Umarul FarookPosted Jan 22, 2016, 10:29 AM
this is really helpfull
KaustubhPosted Jan 15, 2016, 11:29 PM
nice
Ankit SaxenaPosted Jan 11, 2016, 8:40 AM
Good informative post. Thanks for sharing..
Joe WilsonPosted Jan 2, 2016, 5:39 AM
Thank you very much.
Yavuz MercanPosted Dec 16, 2015, 9:16 AM
good article my friend thanks
Anu VPosted Oct 28, 2015, 7:06 AM
good article sir.. thanks
Adama payePosted Oct 13, 2015, 12:36 PM
Your resources are great from beginner to Expert.
Mohamed Gani MnPosted Oct 10, 2015, 9:46 PM
Nice article
Certil RemyPosted Oct 4, 2015, 2:35 PM
Great , thanks for this one
Zubair AhmadPosted Sep 18, 2015, 12:21 AM
Very helpful articl sir .....thanku
Ajeet MishraPosted Sep 1, 2015, 4:12 AM
usefull one
Yashwanth MuthineniPosted Aug 17, 2015, 1:28 AM
Good one sir ..
Varun GuptaPosted Aug 3, 2015, 8:17 AM
very useful..thanks
Cathy RobersonPosted Jul 24, 2015, 6:10 AM
Your blog has been a great help to me moving towards a paperless lifestyle. I’m still refining and trying to get it just right but I feel I’m making progress.
Arun SutharshanPosted Jul 15, 2015, 11:05 AM
Very useful - thanks
Govinda Rajulu YemineniPosted Jul 14, 2015, 5:07 AM
Nice one Sir
Upendra Pratap ShahiPosted Jun 30, 2015, 2:22 AM
nice one sir..
Mahesh SharmaPosted Jun 17, 2015, 2:17 AM
Thanks Sir
Abdul Momin Tasleem AnsariPosted Jun 10, 2015, 8:52 AM
Thanks its a useful Information
Khargesh RajputPosted Jun 1, 2015, 7:16 AM
helpful article on xml sir
Mahesh ChandPosted May 30, 2015, 7:09 AM
Thank you for all comments guys. Please post questions on the forums that are non related to the article.
Amit SamnaniPosted May 29, 2015, 8:14 AM
i really like your this article so amazingly explained with example ...nice sir keep it up
Haribansh Kumar AgrawalPosted May 19, 2015, 10:51 AM
Well Explained Sir
Shailesh UkePosted May 19, 2015, 2:07 AM
nice.,..
Md. Raskinur RashidPosted Jan 10, 2015, 12:14 PM
It's really helpful!
Bala MuruganPosted Oct 15, 2013, 9:12 AM
Hi, Your article is really helpful for us. Having one query working on Text fie to xml.i have created textfile in notepad which having bulk number of records this textfile should converted into xml.
Gaurav ChhabraeditedPosted Mar 8, 2013, 6:17 PMEdited Mar 8, 2013, 6:19 PM
Thanks a lot for your help,But how can i access data if i have different hierarchy of Nodes like..<?xml version="1.0" encoding="utf-8" ?> <pregunta><categoria name="producto"><punto value ="5"><item>¿Qué es Berocca Plus</item><options><option correct ="false">Una Vitamina</option><option correct ="true">Fórmula única con vitaminas de complejo B, Vitamina C, Calcio, Magnesio y Zinc que ayudarán a mejorar tu rendimiento mental</option><option correct ="false">Es vitamina c</option><option correct ="false">Es un estimulante</option></options></punto><punto value ="10"><item>¿Qué hace Berocca?</item><options><option correct ="true">Ayuda a mejorar el rendimiento físico y mental, manteniéndonos en buen estado para que puedan responder ante situaciones de exigencia</option><option correct ="false">Te mantiene despierto porque tiene cafeína</option><option correct ="false">Combate la caída de cabello</option><option correct ="false">Es un suplemento para mujeres embarazadas que ayuda a prevenir malformaciones en bebés</option></options></punto></categoria><!--Para Categoria Consumidor--><categoria name ="consumidor"><punto value ="5"><item>Cómo es el consumidor típico de Berocca Plus</item><options><option correct ="false">Hombres mayores entre 54 y 70</option><option correct ="false">Hombres con enfermedades relacionadas a la edad, 70 años a mas </option><option correct ="true">Es vitamina c</option><option correct ="false">Es un estimulante</option></options></punto></categoria> </pregunta>/* End Of XML */ Here i want display the data like for Punto value =5 or 10 depend upon condition. In short i want access Multiple Nodes Hierarchy. and yes i am .Net Platform Windows Application using C# Thanks a lot in Advance...
muktesh kumarPosted Feb 18, 2013, 2:38 PM
Use below code reading xml file in vb.net . I think that this is the best way to parse or read xml file .net . Dim xmlFile As XmlReader xmlFile = XmlReader.Create("author.xml") Dim ds As New DataSet Dim dv As DataView ds.ReadXml(xmlFile) dv = New DataView(ds.Tables(0)) dv.Sort = "AuthorId" dv.RowFilter = "FirstName='Muktesh' and LastName='Kumar'" Console.write(dv.Item(0).Item("AuthorId").ToString()) See detail implementation here http://techathon.mytechlabs.com/read-xml-file-in-dot-net/
Guest UserPosted Feb 15, 2013, 12:17 PM
It's way better to use dataset for reading and writing an xml file. Then we could leverage the Intellesense feature of Visual Studio and it improves the readability for the poor guy who will need to work on this code in future.
hassan wasefPosted Oct 7, 2012, 1:41 PM
lots of thanks :)
hassan wasefPosted Oct 7, 2012, 1:41 PM
lots of thanks :)
Chandra mouliPosted Sep 17, 2012, 3:45 PM
Thanks and both content and the suggested book are awesome
rushdy najathPosted Aug 23, 2012, 5:32 AM
HOW do i add a type in a xmlElement eg <message type="order">
ken shouferPosted Aug 9, 2012, 11:16 AM
Thanks Mahesh. This article helped me with my C# project.
druva kumar mPosted Apr 26, 2012, 2:55 AM
Hi, i have a query regarding accessing a specific node in a XML file since i m very new to this,please help me out the following is the XML <?xml version="1.0" encoding="UTF-8" ?> - <!-- API root file --> - <API_ROOT xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="$RDFPATH$/pdu.xsd" PART2_STANDARD_VERSION="2.2.0"> - <API> <SHORT_NAME>API_$UVERSION$</SHORT_NAME> <DESCRIPTION>API Implementation</DESCRIPTION> <SUPPLIER_NAME>AG</SUPPLIER_NAME> <LIBRARY_FILE URI="file:/$INSTPATH$/API_$VERSION$.dll" /> <MODULE_DESCRIPTION_FILE URI="file:/$INSTPATH$/MDF_API_$VERSION$.xml" /> <CABLE_DESCRIPTION_FILE URI="file:/$INSTPATH$/CDF_API_$VERSION$.xml" /> </API> </API_ROOT> i want to access or need to get the path and details of the nodes it has to display shortname,DESCRIPTION,SUPPLIER_NAME,LIBRARY_FILE URI etc...
Mahesh ChandPosted Apr 23, 2012, 7:05 AM
I also recommend reading this free book: http://www.c-sharpcorner.com/Ebooks/Free/51/programming-xml-with-C-Sharp.aspx
Mahesh ChandPosted Apr 23, 2012, 7:04 AM
To add, insert, change and remove elements, look at XmlNode class. This class is parent of all XmlElement and other classes. It has methods like InsertAfter, RemoveChild, ReplaceChild and RemoveAll. You can use InsertAfter to insert a node and so on. I will try to write an article on this.
peleg kPosted Oct 21, 2011, 8:04 AM
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;
CrishPosted Mar 29, 2011, 2:04 AM
good article for XML reading, writing etc
Nidheesh BabyPosted Mar 29, 2011, 12:00 AM
how to create inotifypropertychanged class in C#
TeenaPosted Mar 23, 2011, 4:57 AM
Hi sir, I am a beginner in s/w field and this article really helped me a lot in learning xml in C#.
bennnyraja aPosted Mar 1, 2011, 3:31 AM
Pls help me........ How to Read XML File and Insert into SQL Table in Windows service......
naveen PuramPosted Feb 27, 2011, 9:12 PM
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
Venkatgiri SridharaneditedPosted Feb 9, 2011, 4:51 AMEdited Feb 9, 2011, 4:59 AM
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...
Venkatgiri SridharanPosted Feb 9, 2011, 4:44 AM
How to use richtextbox in wpf?
asdas adasdPosted Jan 30, 2011, 10:18 AM
This is beautiful. Thank you. I will follow this in my application
bougie azmehPosted Oct 18, 2010, 8:26 AM
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.
Amit BhallaPosted Oct 14, 2010, 10:14 PM
This is really helpful, really appreciate your efforts to post such a useful information. Thanks, Amit
Blake BartlettPosted Oct 11, 2010, 6:46 AM
Too bad there isn't any example xml files so I could follow this without starting a new project.
ChitranjanPosted Aug 25, 2010, 5:26 AM
Good article. Thanks.
ranjay singhPosted Aug 10, 2010, 8:25 AM
<?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();
anamika singhPosted Jul 7, 2010, 2:03 AM
Thanks a lot for such a nice article.
kuwar prateekPosted Jun 15, 2010, 3:06 AM
hello mahesh ji you aree brilliant and your code gives many developers a neww way to programming
JoPosted May 3, 2010, 9:49 AM
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
marlon gerardoPosted Apr 30, 2010, 1:09 PM
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
sam sdfjPosted Apr 27, 2010, 2:18 PM
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
William ThompsonPosted Apr 25, 2010, 11:01 PM
this is hogwash. You have to close a file after readint it.
newbetonet newbetonetPosted Feb 3, 2010, 7:15 PM
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.
Surendra babu SelvakumarPosted Jan 15, 2010, 10:33 AM
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
Phuong NguyenPosted Jan 13, 2010, 11:04 PM
How to build xml file with embeded schema? thanks
MiriPosted Jan 13, 2010, 2:46 PM
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
KaidoeditedPosted Jan 7, 2010, 4:07 PMEdited Jan 7, 2010, 4:08 PM
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 :)
xxx xxxPosted Jan 2, 2010, 3:19 PM
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) //{ //} } } } }
kris yPosted Dec 29, 2009, 11:31 AM
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?
azmieditedPosted Dec 23, 2009, 11:33 PMEdited Nov 7, 2010, 4:52 PM
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 [email protected] Best wisches and happy holiday AZMI
usman butteditedPosted Dec 12, 2009, 5:53 AMEdited Dec 12, 2009, 5:54 AM
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....
gaurav vermaPosted Dec 10, 2009, 5:15 AM
aa
udayakumar vPosted Nov 28, 2009, 11:25 PM
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...
c cPosted Nov 11, 2009, 2:55 AM
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
xtorm lordeditedPosted Sep 8, 2009, 3:15 AMEdited Sep 11, 2009, 2:14 AM
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..
LewisPosted Sep 2, 2009, 9:42 AM
thank you very much it was a very nice way to get into XML :)
sunit bhargavaPosted Jun 15, 2009, 12:31 PM
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
sunit bhargavaPosted Jun 15, 2009, 12:29 PM
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
CHANDRA BHASKARPosted Jun 12, 2009, 7:08 AM
I AM VERY PLEASED AND THANKS WITH THIS ARTICAL
ramla beeviPosted Apr 20, 2009, 12:46 AM
GOOD ARTICLE
Noel DowlingPosted Apr 16, 2009, 2:48 AM
Much appreciated.
Srikrishna MurthyPosted Apr 9, 2009, 2:31 AM
HI Mahesh, Its a superb materail ..Beautifuuly given the concepts with the programs,,,, I liked it... Thanks, M.Srikrishna Murthy
MohamedPosted Apr 2, 2009, 1:16 PM
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
Aysh AlhroobPosted Mar 23, 2009, 9:11 AM
Could you help me to get the code which can read the xml code that produced from UML sequence diagram by MagicDraw.
lovely nehaPosted Mar 2, 2009, 12:42 AM
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?
poster commnetereditedPosted Oct 23, 2008, 6:18 AMEdited Oct 23, 2008, 6:18 AM
xml reading and writing using array list as a record http://probedeep.blogspot.com/2008/10/program-to-read-and-write-xml-files-in.html
AksarPosted Oct 16, 2008, 3:03 PM
Its a Wonderful Article, Thanks!!!! It is very helpful for new in xml.
Marcos GonzalezPosted Sep 22, 2008, 6:16 PM
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.
NEWMANPosted Aug 18, 2008, 5:03 AM
Do u ve ay sample application reg this....im new to xml in c#.
NEWMANPosted Aug 18, 2008, 5:02 AM
Do u ve ay sample application reg this....im new to xml in c#.
Hameed AsimPosted Mar 15, 2008, 3:45 AM
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
KarthikPosted Feb 21, 2008, 11:54 PM
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?
srikanth keditedPosted Oct 16, 2007, 3:08 AMEdited Oct 19, 2007, 12:57 AM
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
nagarakesh vallamkonduPosted Oct 14, 2007, 3:15 PM
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
Mahesh ChandPosted Aug 14, 2007, 9:24 AM
?