Wednesday, October 17, 2007

Writing data into XML files

You can use XmlTextWriter to write XML. XmlTextwriter is an implementation of the XmlWriter class. This class provides number of validatins to make sure xml is well formed. Here is the code to create a XML file.

using System.Xml;



XmlTextWriter myXmlTextWriter = new XmlTextWriter("student.xml", null);

myXmlTextWriter.Formatting = Formatting.Indented;
myXmlTextWriter.WriteStartDocument(false);
myXmlTextWriter.WriteDocType("students", null, "students.dtd", null);
myXmlTextWriter.WriteComment("This file represents a student in the institute");
myXmlTextWriter.WriteStartElement("students");
myXmlTextWriter.WriteStartElement("student", null);
myXmlTextWriter.WriteAttributeString("id","BCS00094");
myXmlTextWriter.WriteAttributeString("category", "Bsc");
myXmlTextWriter.WriteAttributeString("course", "Computer Science");
myXmlTextWriter.WriteElementString("birthdate", null, "1979-05-22");
myXmlTextWriter.WriteStartElement("Name", null);
myXmlTextWriter.WriteElementString("first-name", "Shawn");
myXmlTextWriter.WriteElementString("last-name", "Tait");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteElementString("GPA", "4.55");
myXmlTextWriter.WriteEndElement();
myXmlTextWriter.WriteEndElement();

myXmlTextWriter.Flush();
myXmlTextWriter.Close();


WriteStartDocument(Boolean) - writes the xml declaration with the version 1.0 and the standalone attribute.
WriteComment - writes a comment containing the specified text.
WriteStartElement - writes the specified start tag.
WriteElementString - writes an element containing a string value.
WriteEndElement - writes the specified end tag.
WriteAttributeString - writes an attribute with a specified value.

No comments:

Post a Comment