How do I convert the XML in an XDocument to a MemoryStream, without saving anything to disk?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答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);
}
}
回答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.
回答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);
}