Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I turn an XDocument into a Stream? [duplicate]

How do I convert the XML in an XDocument to a MemoryStream, without saving anything to disk?

like image 621
mickyjtwin Avatar asked Apr 15 '09 03:04

mickyjtwin


3 Answers

In .NET 4 and later, you can Save it to a MemoryStream:

Stream stream = new MemoryStream();
doc.Save(stream);
// Rewind the stream ready to read from it elsewhere
stream.Position = 0;

In .NET 3.5 and earlier, you would need to create an XmlWriter based on a MemoryStream and save to that, as shown in dtb's answer.

like image 197
Jon Skeet Avatar answered Sep 22 '22 19:09

Jon Skeet


Have a look at the XDocument.WriteTo method; e.g.:

using (MemoryStream ms = new MemoryStream())
{
    XmlWriterSettings xws = new XmlWriterSettings();
    xws.OmitXmlDeclaration = true;
    xws.Indent = true;

    using (XmlWriter xw = XmlWriter.Create(ms, xws))
    {
        XDocument doc = new XDocument(
            new XElement("Child",
                new XElement("GrandChild", "some content")
            )
        );
        doc.WriteTo(xw);
    }
}
like image 41
dtb Avatar answered Sep 21 '22 19:09

dtb


XDocument doc = new XDocument(
    new XElement(C_ROOT,
        new XElement("Child")));
using (var stream = new MemoryStream())
{
    doc.Save(stream);
    stream.Seek(0, SeekOrigin.Begin);
}
like image 36
Saimon2k Avatar answered Sep 18 '22 19:09

Saimon2k