Convert XDocument to Stream

44,324

Solution 1

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

Solution 2

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.

Solution 3

XDocument doc = new XDocument(
    new XElement(C_ROOT,
        new XElement("Child")));
using (var stream = new MemoryStream())
{
    doc.Save(stream);
    stream.Seek(0, SeekOrigin.Begin);
}
Share:
44,324
mickyjtwin
Author by

mickyjtwin

.NET Software Engineer

Updated on August 23, 2020

Comments

  • mickyjtwin
    mickyjtwin over 3 years

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

  • Marc Gravell
    Marc Gravell about 15 years
    Or .Save - but the example holds ;-p
  • Daniel Fortunov
    Daniel Fortunov about 14 years
    @Marc What's the difference between WriteTo() and Save()?
  • Feidex
    Feidex about 14 years
    @Daniel Fortunov: .Save provides more overloads, but all of these end up calling .WriteTo
  • beanmf
    beanmf over 6 years
    I wonder if both approaches add \r\n and whitespace. It would be great to have an easy option here (rather than overload the existing XmlWriter)