如何将xmldocument保存到流中

时间:2012-10-01 15:37:10

标签: c# xmldocument xmlreader

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

问题是如何将我的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....... } }

4 个答案:

答案 0 :(得分:38)

您可以尝试使用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

答案 1 :(得分:1)

写入文件:

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

答案 2 :(得分:0)

试试这个

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

答案 3 :(得分:0)

我意识到这是一个老问题,但认为值得添加一个方法nice little blog post。这样就省去了一些性能较差的方法。

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