how to save xmldocument to a stream

user1711383 picture user1711383 · Oct 1, 2012 · Viewed 61.8k times · Source

I've already written code to parse my xml file with an XmlReader so I don't want to rewrite it. I've now added encryption to the program. I have encrypt() and decrypt() functions which take an xml document and the encryption algorithm. I have a function that uses an xml reader to parse the file but now with the xml document I'm not sure how to create the xmlreader.

The question is how to save my xml document to a stream. I'm sure it's simple but I don't know anything about streams.

XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.Load(filep);
        Decrypt(doc, key);

        Stream tempStream = null;
        doc.Save(tempStream);   //  <--- the problem is here I think

        using (XmlReader reader = XmlReader.Create(tempStream))  
        {
            while (reader.Read())
            { parsing code....... } }

Answer

Aghilas Yakoub picture Aghilas Yakoub · Oct 1, 2012

You can try with MemoryStream class

XmlDocument xmlDoc = new XmlDocument( ); 
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );

xmlStream.Flush();//Adjust this if you want read your data 
xmlStream.Position = 0;

//Define here your reading