C# 将 XDocument 转换为流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/750198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:43:29  来源:igfitidea点击:

Convert XDocument to Stream

c#.netxmllinq-to-xml

提问by mickyjtwin

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

如何将 XDocument 中的 XML 转换为 MemoryStream,而不将任何内容保存到磁盘?

采纳答案by dtb

Have a look at the XDocument.WriteTomethod; e.g.:

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

回答by Jon Skeet

In .NET 4 and later, you can Save it to a MemoryStream:

在 .NET 4 及更高版本中,您可以将其保存到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 XmlWriterbased on a MemoryStreamand save to that, as shown in dtb's answer.

在 .NET 3.5 及更早版本中,您需要XmlWriter基于 a创建一个MemoryStream并保存到其中,如dtb 的回答所示。

回答by Saimon2k

XDocument doc = new XDocument(
    new XElement(C_ROOT,
        new XElement("Child")));
using (var stream = new MemoryStream())
{
    doc.Save(stream);
    stream.Seek(0, SeekOrigin.Begin);
}