Thursday, August 30, 2007

Creating XML Documents in Memory to read them into String

In the previous post on Writing XML Documents with XMLTextWriter Class, I have given sample code for writing the XML to an XML file.

But what 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!!

2 comments:

Anonymous said...

Hello. This post is likeable, and your blog is very interesting, congratulations :-). I will add in my blogroll =). If possible gives a last there on my blog, it is about the Servidor, I hope you enjoy. The address is http://servidor-brasil.blogspot.com. A hug.

Amit Malhotra said...

Great stuff!

 
Dotster Domain Registration Special Offer