0

"Object reference not set to an instance of an object."当我尝试将值保存到 XML 文件时收到错误消息。我已经尝试过一段时间了。我知道它有效,因为我使用相同的代码(略有不同)将其他值保存到该文件中。这是唯一不工作的。

public void SAVEtxtDestination(string txtFileStuff)
{
    XmlDocument myXmlDocument = new XmlDocument();
    myXmlDocument.Load("C:\\Users\\fthompson11\\WebFile.xml");


    XmlNode root = myXmlDocument.DocumentElement;
    var targetKey = "Path";
    XmlNode node = root.SelectSingleNode(string.Format("Text[@Key = '{0}']", targetKey));
    node.Attributes["Value"].Value = txtFileStuff;
    myXmlDocument.Save("C:\\Users\\fthompson11\\WebFile.xml");
}

这是我的 XML 文件的样子:

<?xml version="1.0" encoding="utf-8"?>
<!--This is to write the connection strings, text file location, and report destination.-->
<AdminPaths>
  <AdminPath Name="sqlConnection1" connectionString="tacohell" />
  <TextPath>
    <Text Key="Path" Value="Test3" />
    <Text Key="Report" Value="Test2" />
  </TextPath>
</AdminPaths>
4

1 回答 1

0

在您的评论中,您说在示例中表示小写“v”的值nodes.attributes["value"].Value是大写。Linq to XML 区分大小写,请确保代码中的属性名称与文件中的属性名称完全匹配。

于 2013-04-11T02:08:13.797 回答