Note : This post is first published on Dec-2010 in my previous blog Techkindle. Moving the content here.
Creation of XML file is very much easy with the existing class library in the .NET framework with C#. Although we can create many complex XML files, here I have presented a simple application which is easy to understand, it create & stores the XML file in text file. It retrieves the XML file & displays the data.
using System.Xml; | |
using System; | |
namespace SampleXmlTest | |
{ | |
public class XmlClass | |
{ | |
static void Main(string[] args) | |
{ | |
try | |
{ | |
XmlDocument docxml = new XmlDocument(); //Creating an XmlDocument | |
XmlElement root, rtchild, child; | |
XmlNode nodexml = docxml.CreateNode(XmlNodeType.XmlDeclaration, "", ""); | |
docxml.AppendChild(nodexml);//Adding node to document | |
root = docxml.CreateElement("", "Books", ""); //Creating root element | |
rtchild = docxml.CreateElement("", "Book", "");//Creating 1st child book element | |
child = docxml.CreateElement("", "Name", ""); | |
child.InnerText = "The Last Lecture"; | |
rtchild.AppendChild(child); | |
child = docxml.CreateElement("", "Author", ""); | |
child.InnerText = "Raundy Paush"; | |
rtchild.AppendChild(child); | |
child = docxml.CreateElement("", "Price", ""); | |
child.InnerText = "295"; | |
rtchild.AppendChild(child); | |
root.AppendChild(rtchild);//adding 1st child to root element | |
rtchild = docxml.CreateElement("", "Book", "");//Creating 2nd child book element | |
child = docxml.CreateElement("", "Name", ""); | |
child.InnerText = "The Secret"; | |
rtchild.AppendChild(child); | |
child = docxml.CreateElement("", "Author", ""); | |
child.InnerText = "Rhonda Byrne"; | |
rtchild.AppendChild(child); | |
child = docxml.CreateElement("", "Price", ""); | |
child.InnerText = "660"; | |
rtchild.AppendChild(child); | |
root.AppendChild(rtchild);//adding 2nd child to root element | |
docxml.AppendChild(root);//adding root element to document | |
docxml.Save(@"D:\SampleXml\books.xml");//Saving the xml into Text file | |
Console.WriteLine("Xml Created Successfully"); | |
//Retrieving the XMl file | |
XmlNodeList booklst = docxml.ChildNodes[1].SelectNodes("//Books"); | |
XmlNodeList book = booklst.Item(0).SelectNodes("//Book"); | |
string name1 = book[0].SelectNodes("//Name")[0].InnerText; | |
string author1 = book[0].SelectNodes("//Author")[0].InnerText; | |
string price1 = book[0].SelectNodes("//Price")[0].InnerText; | |
string name2 = book[0].SelectNodes("//Name")[1].InnerText; | |
string author2 = book[0].SelectNodes("//Author")[1].InnerText; | |
string price2 = book[0].SelectNodes("//Price")[1].InnerText; | |
Console.WriteLine(name1); | |
Console.WriteLine(author1); | |
Console.WriteLine(price1); | |
Console.WriteLine(name2); | |
Console.WriteLine(author2); | |
Console.WriteLine(price2); | |
Console.ReadLine(); | |
} | |
catch (Exception ex) | |
{ | |
throw ex; | |
} | |
} | |
} | |
} |
Output
Created XML File:
Retrieved XML data:
Happy Learning 🙂