2013-07-08 38 views
0

我有一个XML文件,我需要写入。我可以成功地做到这一点已经在使用下列内容:写入XML文件并只保存更改

//Code to open the File 
public void Open(string FileName, string FilePath) 
    { 
     try 
     { 
      XmlDoc = new XmlDocument(); 
      XmlDoc.PreserveWhitespace = true; 
      XmlnsManager = new XmlNamespaceManager(mXmlDoc.NameTable); 
      XmlnsManager.AddNamespace("", "urn:xmldata-schema"); 

      FileStream = new FileStream(@Path.Combine(FilePath, FileName), 
       FileMode.Open, FileAccess.ReadWrite); 

      XmlDoc.Load(FileStream); 

     } 
     catch (Exception inException) 
     { 
      MessageBox.Show(inException.ToString()); 
     } 
    } 

    //Code to write to the file 
    public void SetValueByElementName(string Name, string Value) 
    { 
     try 
     { 
      XmlNode node = XmlDoc.SelectSingleNode("//" + inElementID, XmlnsManager); 
      node.InnerText = Value; 

     } 
     catch (Exception inException) 
     { 
      MessageBox.Show(inException.ToString()); 
     } 
    } 

//Code to save the file 
public void Save() 
    { 

     try 
     { 
      XmlDoc.Save(@Path.Combine(XmlFilePath, XmlFileName)); 
      IsFileModified = false; 
     } 
     catch (Exception inException) 
     { 
      MessageBox.Show(inException.ToString()); 
     } 
    } 

然而,这个类的实现,是每一个我需要写一些东西到XML文件的时候,我一定要救它。现在,我被告知必须改变这种情况,而发生的事情是,我必须只保存一次,这在阅读/写作完成时最终完成。我怎样才能做到这一点?

编辑:

我忘了补充一点:有一点我不太明白的是,实施要求立即关闭该文件流。

//Code to close stream 
private void CloseStream() 
    { 
     try 
     { 
      FileStream.Close(); 
     } 
     catch (Exception inException) 
     { 
      MessageBox.Show(inException.ToString()); 
     } 
    } 

的流程如下:

  1. 的OpenFile(然后立即关闭它)
  2. CloseFile
  3. SetFirstElementValueByElementId(改变的东西在XML文件)。
  4. SaveFile(每次我进行更改时都必须调用,否则它们不会反映在文件上)。
+0

我不明白你的问题。为什么不保存XML文件的实例?那么你将能够在运行时改变一切,并最终保存?你能添加更多的信息吗? – user844541

回答

1

只是生命周期分为三个部分:

  • 加载XML文件(我会建议使用LINQ to XML,而不是旧XmlDocument API,但无论你需要做的...)
  • 执行所有你需要
  • 保存在年底

你还没有真正解释正在发生的事情次修改Ë中间的一步,但有两个潜在的选择:

  • 要么你可以让你的代码的其余部分了解XML直接
  • 可以隐藏在另一个类中的XML - 所以你最好有一个XmlDocumentXDocument作为类的成员变量,并调用代码看起来是这样的:

    Foo foo = Foo.Load("test.xml"); 
    // Whatever you need here... 
    foreach (var data in someSource) 
    { 
        foo.UpdateWithData(data); 
    } 
    foo.Save("test.xml"); 
    

    这样,需要了解你的XML文件的结构是Foo唯一的类。 (你会重新命名为更合适,当然,什么的。)

0

你可以简单复制的FileStream的内容到MemoryStream的,直到你想要将文件保存到磁盘使用。

下面的链接解释了如何做到这一点。

Save and load to Memory Stream