我正在尝试使用此函数将值写入 XML 文件。我保留 sql_connection 下的值,但收到错误“对象引用未设置为对象的实例”。我理解错误的含义,但我不知道如何处理 XML 文件。我应该如何解决这个问题?当我单步执行我的代码时,它停在 myNode.Value = sql_connection; 它说我返回一个空值,但 sql_connection 看到我在管理页面上输入的值。提前致谢。
public void SAVEsqlConnection(string sql_Connection)
{
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load("C:\\Users\\fthompson11\\WebFile.xml");
XmlNode root = myXmlDocument.DocumentElement;
XmlNode myNode = root.SelectSingleNode("/connectionString");
myNode.Value = sql_Connection;
myXmlDocument.Save("C:\\Users\\fthompson11\\WebFile.xml");
}
我也试过这样做:
public void SAVEsqlConnection(string sql_Connection)
{
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load("C:\\Users\\fthompson11\\WebFile.xml");
string connectionStringXPath = "/ConnectionStrings/add[@connectionString=\"{0}\"]";
connectionStringXPath = string.Format(connectionStringXPath, sql_Connection);
XmlNode node = myXmlDocument.SelectSingleNode(connectionStringXPath);
node.Attributes["ConnectionStrings"].Value = sql_Connection;
myXmlDocument.Save("C:\\Users\\fthompson11\\WebFile.xml");
}
干得好:
<?xml version="1.0" encoding="UTF-8"?>
<!--This is to write the connection string-->
-<ConnectionStrings> <add connectionString="asdf" Name="sqlConnection1"/> </ConnectionStrings>