Friday 29 July 2011

Creating an Xml document using XmlWriter in C Sharp

The following is the sample code to create xml document using c sharp
FileStream fs = new FileStream("products.xml", FileMode.Create);

XmlWriter w = XmlWriter.Create(fs);

w.WriteStartDocument();
w.WriteStartElement("products");

w.WriteStartElement ("product");
w.WriteAttributeString("id", "1001");
w.WriteElementString("productName", "Gourmet Coffee");
w.WriteElementString("productPrice", "0.99");
w.WriteEndElement();

w.WriteStartElement("product");
w.WriteAttributeString("id", "1002");
w.WriteElementString("productName", "Tea Pot");
w.WriteElementString("productPrice", "12.99");
w.WriteEndElement();

w.WriteEndElement();
w.WriteEndDocument();
w.Flush();
fs.Close();

We can write it also by using XmlTextWriter. the following is the sample code is using XmlTextWriter
// prepare and write XML document
using (StringWriter writer = new StringWriter())
{
using (XmlTextWriter doc = new XmlTextWriter(writer))
{
// prepare XML header items
doc.Formatting = Formatting.Indented;
doc.WriteComment(”Summarized Incoming Call Stats”);
doc.WriteStartElement(”contacts”);
// join calls with contacts data
foreach (Contact con in contacts)
{
if (callGroups.ContainsKey(con.Phone))
{
List calls = callGroups[con.Phone];
// calculate the total call duration and average
long sum = 0;
foreach (CallLog call in calls)
sum += call.Duration;
double avg = (double)sum / (double)calls.Count;
// write XML record for this contact
doc.WriteStartElement(”contact”);
doc.WriteElementString(”lastName”,
con.LastName);
doc.WriteElementString(”firstName”,
con.FirstName);
doc.WriteElementString(”count”,
calls.Count.ToString());
doc.WriteElementString(”totalDuration”,
sum.ToString());
doc.WriteElementString(”averageDuration”,
avg.ToString());
doc.WriteEndElement();
}
}
doc.WriteEndElement();
doc.Flush();
doc.Close();
}
Console.WriteLine(writer.ToString());
}

No comments:

Post a Comment