Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save xmldocument to a stream

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....... } }
like image 355
user1711383 Avatar asked Oct 01 '12 15:10

user1711383


People also ask

Should I use XDocument or XmlDocument?

XDocument is from the LINQ to XML API, and XmlDocument is the standard DOM-style API for XML. If you know DOM well, and don't want to learn LINQ to XML, go with XmlDocument . If you're new to both, check out this page that compares the two, and pick which one you like the looks of better.

Is XmlDocument disposable?

XmlDocument can't be disposed because it does not implement IDisposable . The real question is why do you want to destroy the object? If you don't keep a reference to the object, the garbage collector will get rid of it.

What's the difference between XmlDocument and XmlReader?

Based on my understanding of the two classes, XmlReader should perform faster in my scenario because it reads through an XML document only once, never storing more than the current node in memory. On the contrary, XmlDocument stores the whole XML file in memory which has some performance overhead.


1 Answers

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
like image 198
Aghilas Yakoub Avatar answered Sep 21 '22 12:09

Aghilas Yakoub