Groups | Blog | Home
all groups > dotnet xml > september 2004 >

dotnet xml : XmlSerializer and MemoryStream


grs
9/17/2004 10:01:13 AM
I am using some Microsoft examples that:
1. Serialize an object using XmlSerializer and write a file out to the
harddrive.
2. Read back in the file using XmlDocument.Load and populate a string.

What I would like to do is use MemoryStream to do this instead of writing
to the harddrive, but I am lost in the readers, writers etc.
Can someone show me how to to this using a memory stream.

thanks
grs

// Code to accept eConnectType object and write to a disk file
public void WriteObjectsToFile(string fileName,eConnectType
objectToSerialize)
{
try
{
XmlSerializer xmlSerializer = new
XmlSerializer(objectToSerialize.GetType());
XmlTextWriter xmlTextWriter = new XmlTextWriter(fileName,null);
xmlSerializer.Serialize(xmlTextWriter,objectToSerialize);
xmlTextWriter.Close();
}

// code reading the file and creating the string.
string aXmlString;
try
{
// Load the written xml document
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(fileName);
aXmlString = xmlDocument.OuterXml;

M. Said
9/17/2004 11:33:47 AM

This should work:


// Create the stream.
MemoryStream ms = new MemoryStream();

XmlSerializer s = new XmlSerializer(objectToSerialize.GetType());
XmlTextWriter tw = new XmlTextWriter(ms,null);
s.Serialize(xmlTextWriter,objectToSerialize);

// Rewind the Stream.
ms.Seek(0,SeekOrigin.Begin);

XmlDocument doc = new XmlDocument();
// load from stream;
doc.Load(m);
String xmlString = xmlDocument.OuterXml;

Reagrds,


[quoted text, click to view]
grs
9/17/2004 1:43:57 PM
M. Said,
I thank you, I had exactly the same code as you recommended BUT
I did not Rewind the Stream !! I would have struggled forever.
grs


[quoted text, click to view]

M. Said
9/17/2004 8:35:54 PM
Ya, when I think of Streams, I always think of a VCR tape. If you record a
show, you must rewind to play it. (i.e. read it.) Otherwise, you get nothing
(or some other show) <g>

Good luck.

[quoted text, click to view]

AddThis Social Bookmark Button