Skip to content

Instantly share code, notes, and snippets.

@gopigujjula
Created April 18, 2013 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gopigujjula/5412723 to your computer and use it in GitHub Desktop.
Save gopigujjula/5412723 to your computer and use it in GitHub Desktop.
XML generation using XMLDocument
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment