Sunday, November 16, 2008

Creating XML Documents in Memory to read them into String

 if you wish to create the XML document in memory and use it as a string. I've also included in the sample the way to create well-formatted(indented) XML document with XmlTextWriter.

Here is the trick.

You could use MemoryStream class to create the XML document and later use it as a string.

MemoryStream memoryStreamObject = new
MemoryStream();

XmlTextWriter xmlTextWriterObject = new
XmlTextWriter(memoryStreamObject, System.Text.Encoding.UTF8);

xmlTextWriterObject.Formatting = Formatting.Indented;

xmlTextWriterObject.IndentChar = '\t';

xmlTextWriterObject.Indentation = 1;

    xmlTextWriterObject.WriteStartDocument();    

//here goes entire code to build the XML document

    xmlTextWriterObject.WriteEndDocument();

    xmlTextWriterObject.Flush(); //write the XML content to MemoryStream and close writer

memoryStreamObject.Position = 0;

    StreamReader sr = new
StreamReader(memoryStreamObject);

    String output = sr.ReadToEnd();    //reads entire content from the stream to string

//now use the string into your program

That's it. So, you could use the create string representation of XML in your .NET Application like saving it into Database or pass it onto another module.

Enjoy Xmling!!

No comments: