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 XmlTextWriter xmlTextWriterObject = new 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 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!!
MemoryStream();
XmlTextWriter(memoryStreamObject, System.Text.Encoding.UTF8);
StreamReader(memoryStreamObject);
Thursday, August 30, 2007
Creating XML Documents in Memory to read them into String
Posted by chirag at 6:51 PM
Labels: .NET Examples, ASP .NET, C# .NET, XML
Subscribe to:
Post Comments (Atom)
2 comments:
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.
Great stuff!
Post a Comment