我有一个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());
}
}
的流程如下:
- 的OpenFile(然后立即关闭它)
- CloseFile
- SetFirstElementValueByElementId(改变的东西在XML文件)。
- SaveFile(每次我进行更改时都必须调用,否则它们不会反映在文件上)。
我不明白你的问题。为什么不保存XML文件的实例?那么你将能够在运行时改变一切,并最终保存?你能添加更多的信息吗? – user844541