user1711383
user1711383

Reputation: 828

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....... } }

Upvotes: 19

Views: 79076

Answers (4)

Martin_W
Martin_W

Reputation: 1787

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));
}

Upvotes: 2

Kosmas
Kosmas

Reputation: 385

try this

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

Upvotes: 0

PReghe
PReghe

Reputation: 11

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);
        }
    }

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

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

Upvotes: 51

Related Questions