Tuesday, August 09, 2005

Using XMLWriter to create XML Documents

If you want to generate an in-memory XML Document i.e. without creating a file on system you can use System.IO.StringWriter class to provide IO stream to an XMLTextWriter instance. Following is a code snippet that I used to create an XML Document.


this.returnMessage = new System.Xml.XmlDocument();

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(stringWriter);
xmlTextWriter.WriteStartDocument();

xmlTextWriter.WriteStartElement("Message");

#region Header
xmlTextWriter.WriteStartElement("Header");
// CLIENT ID
xmlTextWriter.WriteStartElement("Client");
xmlTextWriter.WriteAttributeString("","Id","",this.clientId);
xmlTextWriter.WriteEndElement();
/// CALL ID
xmlTextWriter.WriteStartElement("Call");
xmlTextWriter.WriteAttributeString("","Id","",this.callId);
xmlTextWriter.WriteEndElement();
/// DESCRIPTION
xmlTextWriter.WriteStartElement("Description");
xmlTextWriter.WriteAttributeString("","text","",this.description);
xmlTextWriter.WriteEndElement();
// HEADER CLOSE
xmlTextWriter.WriteEndElement();
#endregion

xmlTextWriter.WriteEndElement(); // end message

xmlTextWriter.WriteEndDocument();
xmlTextWriter.Flush();
xmlTextWriter.Close();
stringWriter.Flush();
this.returnMessage.LoadXml(stringWriter.ToString());
stringWriter.Close();

No comments: