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, 6:45 PM EST
CzlonkowieZespolu.Sort((x, y) => x.DataWstapienia.CompareTo(y.DataWstapienia));
Tomasz JablonskiPosted Feb 1, 2023, 6:45 PM EST
Public bool Equals(Osoba? other) { if(Pesel == other.Pesel) { return true; } else { return false; } }
Tomasz JablonskiPosted Feb 1, 2023, 6:45 PM EST
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, 6:44 PM EST
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, 6:43 PM EST
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, 6:42 PM EST
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, 3:38 PM EST
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, 9:37 AM EDT
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 ManogararajahTOP 100Posted Jul 21, 2018, 9:55 PM EDT
Nice article, thank you for sharing
Willie sunPosted May 22, 2018, 12:03 AM EDT
Test this code, the textReader.Read() give out exception, don't know why?
Willie sunPosted May 22, 2018, 12:01 AM EDT
Test this code, the textReader1.Read() give out exception, don't know why?
Satish Kumar VadlavalliPosted Feb 21, 2018, 9:01 PM EST
Great and useful. one
Ganesh MotekarPosted Jul 2, 2017, 9:02 PM EDT
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 12, 2017, 9:43 PM EDT
How to add whitespace and indents while writing xml file
reddy prasadPosted Jan 15, 2017, 8:27 PM EST
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, 3:11 AM EDT
Great article
Ramesh PalaniappanPosted Aug 18, 2016, 4:10 AM EDT
Good One
Shobana JPosted Jul 8, 2016, 12:03 AM EDT
Niceone
kalu singh raoPosted Jul 7, 2016, 4:37 AM EDT
Nice...
Karthik ElumalaiPosted Jul 3, 2016, 8:16 PM EDT
Great and useful. one
Davronbek UmirovPosted Jun 28, 2016, 3:12 AM EDT
Usefull one..
Bhuvanesh MohankumarPosted Apr 19, 2016, 10:30 AM EDT
Good one
Paul FleischerPosted Apr 5, 2016, 4:20 PM EDT
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, 5:11 AM EDT
great
Sumi ArianiPosted Mar 31, 2016, 11:27 PM EDT
thanks mate
Abdul BasithPosted Mar 31, 2016, 2:41 AM EDT
great work
Vignesh ManiTOP 100Posted Mar 21, 2016, 1:07 PM EDT
Nice
Kashif SohailPosted Mar 13, 2016, 7:02 AM EDT
Nice Article Sir
Prashant VermaPosted Mar 9, 2016, 10:13 PM EST
Good one
Prashant VermaPosted Mar 9, 2016, 10:13 PM EST
Nice article
Sirisha KPosted Mar 4, 2016, 4:57 AM EST
Useone
Ammar ShaukatPosted Mar 2, 2016, 7:07 AM EST
Good
Anil JhaPosted Mar 1, 2016, 11:33 PM EST
Well explained
Sonu ChaudharyPosted Feb 25, 2016, 1:28 AM EST
great one
Jithil JohnPosted Feb 15, 2016, 9:07 PM EST
Great
Shailesh UkePosted Feb 15, 2016, 8:52 PM EST
Nice Article
Sr KarthigaPosted Feb 10, 2016, 4:13 AM EST
Good one sir its very intresting
Abhay ShankerPosted Feb 6, 2016, 7:36 AM EST
Nice One.
Irfan AcPosted Jan 24, 2016, 8:15 PM EST
thanks
Umarul FarookPosted Jan 22, 2016, 5:29 AM EST
this is really helpfull
KaustubhPosted Jan 15, 2016, 6:29 PM EST
nice
Ankit SaxenaPosted Jan 11, 2016, 3:40 AM EST
Good informative post. Thanks for sharing..
Joe WilsonPosted Jan 2, 2016, 12:39 AM EST
Thank you very much.
Yavuz MercanPosted Dec 16, 2015, 4:16 AM EST
good article my friend thanks
Anu VPosted Oct 28, 2015, 3:06 AM EDT
good article sir.. thanks
Adama payePosted Oct 13, 2015, 8:36 AM EDT
Your resources are great from beginner to Expert.
Mohamed Gani MnPosted Oct 10, 2015, 5:46 PM EDT
Nice article
Certil RemyPosted Oct 4, 2015, 10:35 AM EDT
Great , thanks for this one
Zubair AhmadPosted Sep 17, 2015, 8:21 PM EDT
Very helpful articl sir .....thanku
Ajeet MishraPosted Sep 1, 2015, 12:12 AM EDT
usefull one
Yashwanth MuthineniPosted Aug 16, 2015, 9:28 PM EDT
Good one sir ..
Varun GuptaPosted Aug 3, 2015, 4:17 AM EDT
very useful..thanks
Cathy RobersonPosted Jul 24, 2015, 2:10 AM EDT
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, 7:05 AM EDT
Very useful - thanks
Govinda Rajulu YemineniPosted Jul 14, 2015, 1:07 AM EDT
Nice one Sir
Upendra Pratap ShahiPosted Jun 29, 2015, 10:22 PM EDT
nice one sir..
Mahesh SharmaPosted Jun 16, 2015, 10:17 PM EDT
Thanks Sir
Abdul Momin Tasleem AnsariPosted Jun 10, 2015, 4:52 AM EDT
Thanks its a useful Information
Khargesh RajputPosted Jun 1, 2015, 3:16 AM EDT
helpful article on xml sir
Mahesh ChandTOP 10Posted May 30, 2015, 3:09 AM EDT
Thank you for all comments guys. Please post questions on the forums that are non related to the article.
Amit SamnaniPosted May 29, 2015, 4:14 AM EDT
i really like your this article so amazingly explained with example ...nice sir keep it up
Haribansh Kumar AgrawalPosted May 19, 2015, 6:51 AM EDT
Well Explained Sir
Shailesh UkePosted May 18, 2015, 10:07 PM EDT
nice.,..
Md. Raskinur RashidPosted Jan 10, 2015, 7:14 AM EST
It's really helpful!
Bala MuruganPosted Oct 15, 2013, 5:12 AM EDT
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, 1:17 PM ESTEdited Mar 8, 2013, 1:19 PM EST
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, 9:38 AM EST
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, 7:17 AM EST
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, 9:41 AM EDT
lots of thanks :)
hassan wasefPosted Oct 7, 2012, 9:41 AM EDT
lots of thanks :)
Chandra mouliPosted Sep 17, 2012, 11:45 AM EDT
Thanks and both content and the suggested book are awesome
rushdy najathPosted Aug 23, 2012, 1:32 AM EDT
HOW do i add a type in a xmlElement eg <message type="order">
ken shouferPosted Aug 9, 2012, 7:16 AM EDT
Thanks Mahesh. This article helped me with my C# project.
druva kumar mPosted Apr 25, 2012, 10:55 PM EDT
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 ChandTOP 10Posted Apr 23, 2012, 3:05 AM EDT
I also recommend reading this free book: http://www.c-sharpcorner.com/Ebooks/Free/51/programming-xml-with-C-Sharp.aspx
Mahesh ChandTOP 10Posted Apr 23, 2012, 3:04 AM EDT
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, 4:04 AM EDT
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 28, 2011, 10:04 PM EDT
good article for XML reading, writing etc
Nidheesh BabyPosted Mar 28, 2011, 8:00 PM EDT
how to create inotifypropertychanged class in C#
TeenaPosted Mar 23, 2011, 12:57 AM EDT
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 Feb 28, 2011, 10:31 PM EST
Pls help me........ How to Read XML File and Insert into SQL Table in Windows service......
naveen PuramPosted Feb 27, 2011, 4:12 PM EST
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 8, 2011, 11:51 PM ESTEdited Feb 8, 2011, 11:59 PM EST
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 8, 2011, 11:44 PM EST
How to use richtextbox in wpf?
asdas adasdPosted Jan 30, 2011, 5:18 AM EST
This is beautiful. Thank you. I will follow this in my application
bougie azmehPosted Oct 18, 2010, 4:26 AM EDT
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, 6:14 PM EDT
This is really helpful, really appreciate your efforts to post such a useful information. Thanks, Amit
Blake BartlettPosted Oct 11, 2010, 2:46 AM EDT
Too bad there isn't any example xml files so I could follow this without starting a new project.
ChitranjanPosted Aug 25, 2010, 1:26 AM EDT
Good article. Thanks.
ranjay singhPosted Aug 10, 2010, 4:25 AM EDT
<?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 6, 2010, 10:03 PM EDT
Thanks a lot for such a nice article.
kuwar prateekPosted Jun 14, 2010, 11:06 PM EDT
hello mahesh ji you aree brilliant and your code gives many developers a neww way to programming
JoPosted May 3, 2010, 5:49 AM EDT
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, 9:09 AM EDT
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, 10:18 AM EDT
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, 7:01 PM EDT
this is hogwash. You have to close a file after readint it.
newbetonet newbetonetPosted Feb 3, 2010, 2:15 PM EST
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, 5:33 AM EST
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, 6:04 PM EST
How to build xml file with embeded schema? thanks
MiriPosted Jan 13, 2010, 9:46 AM EST
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, 11:07 AM ESTEdited Jan 7, 2010, 11:08 AM EST
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, 10:19 AM EST
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, 6:31 AM EST
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, 6:33 PM ESTEdited Nov 7, 2010, 11:52 AM EST
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, 12:53 AM ESTEdited Dec 12, 2009, 12:54 AM EST
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, 12:15 AM EST
aa
udayakumar vPosted Nov 28, 2009, 6:25 PM EST
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 10, 2009, 9:55 PM EST
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 7, 2009, 11:15 PM EDTEdited Sep 10, 2009, 10:14 PM EDT
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, 5:42 AM EDT
thank you very much it was a very nice way to get into XML :)
sunit bhargavaPosted Jun 15, 2009, 8:31 AM EDT
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, 8:29 AM EDT
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, 3:08 AM EDT
I AM VERY PLEASED AND THANKS WITH THIS ARTICAL
ramla beeviPosted Apr 19, 2009, 8:46 PM EDT
GOOD ARTICLE
Noel DowlingPosted Apr 15, 2009, 10:48 PM EDT
Much appreciated.
Srikrishna MurthyPosted Apr 8, 2009, 10:31 PM EDT
HI Mahesh, Its a superb materail ..Beautifuuly given the concepts with the programs,,,, I liked it... Thanks, M.Srikrishna Murthy
MohamedPosted Apr 2, 2009, 9:16 AM EDT
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, 5:11 AM EDT
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 1, 2009, 7:42 PM EST
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, 2:18 AM EDTEdited Oct 23, 2008, 2:18 AM EDT
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, 11:03 AM EDT
Its a Wonderful Article, Thanks!!!! It is very helpful for new in xml.
Marcos GonzalezPosted Sep 22, 2008, 2:16 PM EDT
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, 1:03 AM EDT
Do u ve ay sample application reg this....im new to xml in c#.
NEWMANPosted Aug 18, 2008, 1:02 AM EDT
Do u ve ay sample application reg this....im new to xml in c#.
Hameed AsimPosted Mar 14, 2008, 11:45 PM EDT
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, 6:54 PM EST
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 15, 2007, 11:08 PM EDTEdited Oct 18, 2007, 8:57 PM EDT
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, 11:15 AM EDT
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 ChandTOP 10Posted Aug 14, 2007, 5:24 AM EDT
?