如何将XML文档保存到流中

17

我已经编写了使用 XmlReader 解析 xml 文件的代码,所以不想重写它。现在我已经给程序添加了加密功能。我有一个加密() 和解密() 函数,它们接受一个 xml 文档和加密算法作为参数。我有一个函数使用 xml reader 解析文件,但是现在有了 xml 文档,我不确定如何创建 xml reader。

问题是如何将我的 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个回答

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

6
根据Flush()方法的文档(http://msdn.microsoft.com/en-us/library/system.io.memorystream.flush%28v=vs.110%29.aspx):由于任何写入MemoryStream对象的数据都会被写入RAM,因此该方法是多余的。你应该从你的回答中移除它,因为它本质上是一个“无操作”。 - MarioDS

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

1

我知道这是一个旧问题,但认为值得添加一种方法,来自这个不错的博客文章。这比一些性能较差的方法更胜一筹。

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

0

试一下这个

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接