17

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....... } }
Kit
  • 20,354
  • 4
  • 60
  • 103
user1711383
  • 778
  • 2
  • 11
  • 20

4 Answers4

48

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
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
  • 6
    According to the [docs on the Flush() method](http://msdn.microsoft.com/en-us/library/system.io.memorystream.flush%28v=vs.110%29.aspx): `Because any data written to a MemoryStream object is written into RAM, this method is redundant`. Should remove that from your answer since it is essentially a "noop". – MarioDS Jun 06 '14 at 09:28
1

Writing to a file:

 static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<FTPSessionOptionInfo><HostName>ftp.badboymedia.ca</HostName></FTPSessionOptionInfo>");

        using (StreamWriter fs = new StreamWriter("test.xml"))
        {
            fs.Write(doc.InnerXml);
        }
    }
PReghe
  • 11
  • 1
1

I realize this is an old question, but thought it worth adding a method from this nice little blog post. This edges out some less performant methods.

private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
    return XDocument.Load(new XmlNodeReader(doc));
}
Martin_W
  • 1,582
  • 1
  • 19
  • 24
0

try this

    XmlDocument document= new XmlDocument( );
    string pathTmp = "d:\somepath";
    using( FileStream fs = new FileStream( pathTmp, FileMode.CreateNew ))
    {
      document.Save(pathTmp);
      fs.Flush();
    }
Kosmas
  • 353
  • 4
  • 11