-1

我正在尝试为“另存为...”菜单项编写代码。我的代码如下所示:

private void menuItem9_Click(object sender, EventArgs e)
{
    saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;
    saveFileDialog1.ShowDialog();
    XmlDocument document = new XmlDocument();

    string fileName = saveFileDialog1.FileName.ToString();
    document.Save(fileName+ ".xml");
    if (!File.Exists(fileName))
    {
        File.Create(fileName);
    }
}

所以基本上我想做的是使用“另存为”选项。单击它后,我希望能够将我的 .xml 文件以不同的名称保存在我想要的任何地方。

4

3 回答 3

1

您当前的代码将引发异常,因为您XmlDocument不包含根节点。另请记住,该SaveFileDialog's Filename属性还包含扩展名。

您可以使用创建没有根节点的新文件

SaveFileDialog saveFileDialog1 = new SaveFileDialog();

saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{  
    File.Create(saveFileDialog1.FileName);
}

或者在保存之前确保您的 XmlDocument 有一个根节点:

SaveFileDialog saveFileDialog1 = new SaveFileDialog();

saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    XmlDocument document = new XmlDocument();
    document.AppendChild(document.CreateElement("Root"));
    document.Save(saveFileDialog1.FileName);
}
于 2013-04-14T17:55:39.847 回答
0

您新创建的文档实例XmlDocument没有任何根元素,因此XmlException

您可以避免使用saveFileDialog1.FileName.ToString()assaveFileDialog1.FileName已经是一个字符串值。

这段代码

document.Save(fileName+ ".xml");

应该

document.Save(saveFileDialog1.FileName);
于 2013-04-14T17:57:01.687 回答
0
private void menuItem9_Click(object sender, EventArgs e)
{
    saveFileDialog1.Filter = ".XML file (*.xml)|*.xml";
    saveFileDialog1.FilterIndex = 1;
    saveFileDialog1.RestoreDirectory = true;
    saveFileDialog1.ShowDialog();
    XmlDocument document = new XmlDocument();

    //Add this line of code
    document.LoadXml("<root></root>");

    string fileName = saveFileDialog1.FileName.ToString();
    // Save the document to a file
    XmlTextWriter writer = new XmlTextWriter(fileName,null);
    document.Save(writer);

}
于 2013-04-14T18:06:10.667 回答