Convert XDocument to Stream

后端 未结 3 546
傲寒
傲寒 2020-12-05 09:32

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

3条回答
  •  春和景丽
    2020-12-05 09:59

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

提交回复
热议问题