How do I convert the XML in an XDocument to a MemoryStream, without saving anything to disk?
Asked
Active
Viewed 4.8k times
3 Answers
48
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.

Cody Gray - on strike
- 239,200
- 50
- 490
- 574

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
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) – beanmf Nov 02 '17 at 15:06
31
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);
}
}

Cody Gray - on strike
- 239,200
- 50
- 490
- 574

dtb
- 213,145
- 36
- 401
- 431
-
6
-
2
-
5@Daniel Fortunov: .Save provides more overloads, but all of these end up calling .WriteTo – dtb Mar 01 '10 at 16:59
2
XDocument doc = new XDocument(
new XElement(C_ROOT,
new XElement("Child")));
using (var stream = new MemoryStream())
{
doc.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
}

Saimon2k
- 21
- 3