如何将XDocument中的XML转换为MemoryStream,而不将任何内容保存到磁盘?
答案 0 :(得分:37)
在.NET 4及更高版本中,您可以将其保存到MemoryStream
:
Stream stream = new MemoryStream();
doc.Save(stream);
// Rewind the stream ready to read from it elsewhere
stream.Position = 0;
在.NET 3.5及更早版本中,您需要根据XmlWriter
创建MemoryStream
并保存到该{{1}},如dtb's answer所示。
答案 1 :(得分:28)
查看XDocument.WriteTo方法; 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 :(得分:1)
XDocument doc = new XDocument(
new XElement(C_ROOT,
new XElement("Child")));
using (var stream = new MemoryStream())
{
doc.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
}