Monday, March 25, 2013

Creating and Reading xml in C#

xml in c# Creating  xml in C#

.Net provides 2 ways for creating xml thru. code


1. using XMLTextWriter

2.using DataSet



XMLTextWriter class

here is an example of creating xml using xmltextwriter class

import the following namespaces

using System.Diagnostics;
using System.Xml;
XmlTextWriter xtw;

On the code behind of Button Click , write the following code

xtw = new XmlTextWriter("d:\\Contacts.xml",null);
xtw.WriteStartElement("Contacts");
xtw.WriteStartElement("Contact");
xtw.WriteStartElement("Name");
xtw.WriteString("Shalini");
xtw.WriteEndElement();
xtw.WriteStartElement("Location");
xtw.WriteString("Kochi");
xtw.WriteEndElement();
xtw.Close();
Process.Start("d:\\Contacts.xml", "iexplore");


DataSet class



We can create xml files using DataSet class

import the following namespaces
using System.Diagnostics;
using System.Xml;
using System.Data.SqlClient;
On the code behind of Button Click , write the following code


DataSet ds=new DataSet();

SqlConnection con=new SqlConnection(constring);
SqlDataAdapter ad=new SqlDataAdapter("Select * from student",con);
ad.Fill(ds,"stud");
ds.WriteXml("d:\\a.xml");

Process.Start("Notepad","d:\\a.xml");



Reading xml data using XMLTextReader
--------------------------------------------

here is an xml file

<names>
 <faculty>Blessy</faculty>
 <blog>BlessyS.blogspot.com</blog>
  <faculty>Blety</faculty>
<blog>Blety.blogspot.com</blog>
</names>

to read from this file

XmlTextReader xmlr = new XmlTextReader(@"d:\blessy\xmleg\xmleg\XMLFile2.xml");

private void buttonshow_Click(object sender, EventArgs e)
{
while (xmlr.Read())
{
switch (xmlr.Name)
{
case "faculty":
MessageBox.Show(xmlr.ReadString());
break;

case "blogs":
MessageBox.Show(xmlr.ReadString());
break;

}
}
}

0 comments:

Post a Comment