C# 如何将 xmldocument 保存到流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12676441/
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-10 00:04:33  来源:igfitidea点击:

how to save xmldocument to a stream

c#xmldocumentxmlreader

提问by user1711383

I've already written code to parse my xml file with an XmlReaderso I don't want to rewrite it. I've now added encryption to the program. I have encrypt() and decrypt() functions which take an xml document and the encryption algorithm. I have a function that uses an xml reader to parse the file but now with the xml document I'm not sure how to create the xmlreader.

我已经编写了代码来解析我的 xml 文件,XmlReader所以我不想重写它。我现在已经为程序添加了加密。我有使用 xml 文档和加密算法的 encrypt() 和decrypt() 函数。我有一个使用 xml 读取器来解析文件的函数,但现在使用 xml 文档我不确定如何创建 xmlreader。

The question is how to save my xml document to a stream. I'm sure it's simple but I don't know anything about streams.

问题是如何将我的 xml 文档保存到流中。我确定这很简单,但我对流一无所知。

XmlDocument doc = new XmlDocument();
        doc.PreserveWhitespace = true;
        doc.Load(filep);
        Decrypt(doc, key);

        Stream tempStream = null;
        doc.Save(tempStream);   //  <--- the problem is here I think

        using (XmlReader reader = XmlReader.Create(tempStream))  
        {
            while (reader.Read())
            { parsing code....... } }

采纳答案by Aghilas Yakoub

You can try with MemoryStreamclass

你可以试试MemoryStream上课

XmlDocument xmlDoc = new XmlDocument( ); 
MemoryStream xmlStream = new MemoryStream( );
xmlDoc.Save( xmlStream );

xmlStream.Flush();//Adjust this if you want read your data 
xmlStream.Position = 0;

//Define here your reading

回答by PReghe

Writing to a file:

写入文件:

 static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml("<FTPSessionOptionInfo><HostName>ftp.badboymedia.ca</HostName></FTPSessionOptionInfo>");

        using (StreamWriter fs = new StreamWriter("test.xml"))
        {
            fs.Write(doc.InnerXml);
        }
    }

回答by Kosmas

try this

尝试这个

    XmlDocument document= new XmlDocument( );
    string pathTmp = "d:\somepath";
    using( FileStream fs = new FileStream( pathTmp, FileMode.CreateNew ))
    {
      document.Save(pathTmp);
      fs.Flush();
    }

回答by Martin_W

I realize this is an old question, but thought it worth adding a method from this nice little blog post. This edges out some less performant methods.

我意识到这是一个老问题,但认为值得从这篇漂亮的小博文中添加一个方法。这淘汰了一些性能较差的方法。

private static XDocument DocumentToXDocumentReader(XmlDocument doc)
{
    return XDocument.Load(new XmlNodeReader(doc));
}