将XDocument转换为Stream
如何将XDocument中的XML转换为MemoryStream,而不保存任何内容到磁盘?
看看XDocument.WriteTo方法; 例如:
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); } }
在.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和更早的版本中,你将需要创build一个基于MemoryStream
的XmlWriter
并保存到这个,如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); }