【问题标题】:how to save xmldocument to a stream如何将xmldocument保存到流中
【发布时间】:2012-09-22 11:44:17
【问题描述】:

我已经编写了代码来使用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....... } }

【问题讨论】:

    标签: c# xmldocument xmlreader


    【解决方案1】:

    你可以试试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
    

    【讨论】:

    • 根据docs on the Flush() methodBecause any data written to a MemoryStream object is written into RAM, this method is redundant。应该从你的答案中删除它,因为它本质上是一个“noop”。
    【解决方案2】:

    写入文件:

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

    【讨论】:

      【解决方案3】:

      试试这个

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2019-02-17
          • 1970-01-01
          • 2015-03-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-09-29
          相关资源
          最近更新 更多