简体   繁体   English

无法将更改保存到xml文件

[英]Unable to save changes to xml file

As a learning exercise I'm building a simple Server IP storage and ping monitor application. 作为学习练习,我将构建一个简单的服务器IP存储和ping监视器应用程序。 The application reads a list of servers/hosts from the xml file and displays them to the user and allows them the ability to ping them to check their online status. 该应用程序从xml文件中读取服务器/主机的列表,并将其显示给用户,并使他们能够ping它们以检查其在线状态。

The read and ping functionality works fine but when writing code to add an additional server instance the code won't save the new element to the xml file. 读取和ping功能正常工作,但是在编写代码以添加其他服务器实例时,代码不会将新元素保存到xml文件中。

Here's the basic XML structure in serverlist.xml : 这是serverlist.xml的基本XML结构:

<servers>
  <server name="Operations">
      <hostname>Operations</hostname>
      <hostaddress>address</hostaddress>
  </server>
  <server name="Development">
      <hostname>development</hostname>
      <hostaddress>address</hostaddress>
  </server>
</servers>

And here is the code I've used to add a new server element: 这是我用来添加新server元素的代码:

private void btnAdd_Click(object sender, EventArgs e)
        {
            XDocument xDocument = new XDocument();
            try
            {
                if (txtHostName.Text == "" || txtHostAddress.Text == "")
                {
                    MessageBox.Show("Please complete the fields shown!", "Complete form", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                else
                {
                    // Add element to XML
                    if (File.Exists("serverlist.xml"))
                    {
                        xDocument = XDocument.Load("serverlist.xml");
                    }
                    else
                    {
                        MessageBox.Show("No XML available!", "Error", MessageBoxButtons.OK);
                    }

                    XElement newServer = new XElement("server", txtServerName.Text,
                            new XElement("hostname", txtHostName.Text),
                            new XElement("hostaddress", txtHostAddress.Text));

                    xDocument.Root.Add(newServer);


                    xDocument.Save("Serverlist.xml");
                    MessageBox.Show("Server Added!", "Server Added", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

            }

I'm not seeing any errors or the catch clauses, the element is just not being saved to the XML. 我没有看到任何错误或catch子句,该元素只是没有保存到XML。 This is probably a very simple and silly thing, but I've done a lot of googling(other search engines are available!) and research into XML functions but I can't seem to see what I've missed. 这可能是一件非常简单和愚蠢的事情,但是我做了很多谷歌搜索(可以使用其他搜索引擎!)并研究XML函数,但是我似乎看不到我错过了什么。

Your XML saving code works fine if the "serverList.xml" file contains a valid XML document. 如果“ serverList.xml”文件包含有效的XML文档,则XML保存代码可以正常工作。

I have a few suggestions: 我有一些建议:

  1. If the serverList.xml file does not exist, either return after the "No XML Available!" 如果serverList.xml文件不存在,则在“没有可用的XML!”之后返回。 MessageBox OR create a new XDocument (see below) MessageBox或创建一个新的XDocument(请参见下文)

  2. Use the SetAttribute("name", txtServerName.Text) to create the name="Operations" attribute. 使用SetAttribute(“ name”,txtServerName.Text)创建name =“ Operations”属性。

  3. Make sure you are looking at the right "serverList.xml" file. 确保您正在查看正确的“ serverList.xml”文件。 "serverList.xml" needs to be in the same folder as the .exe that you are running. “ serverList.xml”必须与您正在运行的.exe位于同一文件夹中。 If you are debugging, then "serverList.xml" --> $(ProjectDir)\\bin\\Debug\\serverList.xml 如果要调试,则“ serverList.xml”-> $(ProjectDir)\\ bin \\ Debug \\ serverList.xml

     private void button1_Click(object sender, EventArgs e) { XDocument xDocument = new XDocument(); try { // Add element to XML if (File.Exists(@"C:\\Projects\\serverlist.xml")) { xDocument = XDocument.Load(@"C:\\Projects\\ServerList.xml"); } else { MessageBox.Show("No XML available!", "Error", MessageBoxButtons.OK); // create new document xDocument.Add(new XElement("servers")); } XElement newServer = new XElement("server", new XElement("hostname", txtHostName.Text), new XElement("hostaddress", txtHostAddress.Text)); newServer.SetAttributeValue("name", txtServerName.Text); xDocument.Root.Add(newServer); xDocument.Save(@"C:\\Projects\\Serverlist.xml"); MessageBox.Show("Server Added!", "Server Added", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exc) { MessageBox.Show(exc.ToString(), "Error"); } } 

The issue turned out to be the 'Copy to Output Directory' property for the serverlist.xml file. 原来,该问题是serverlist.xml文件的“复制到输出目录”属性。 This meant that in building/rebuilding the solution during debugging the copy of the xml file was being overwritten with the fresh unmodified original xml file. 这意味着在调试过程中构建/重建解决方案时,xml文件的副本将被未修改的原始xml文件覆盖。 So it didn't look like it had been saved at all, whereas it had but then been overwritten. 因此,它看起来根本没有被保存,但是已经被保存但随后被覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM