この関数を使用して XML ファイルに値を書き込もうとしています。sql_connection の下に値を保持していますが、「オブジェクト参照がオブジェクトのインスタンスに設定されていません」というエラーが表示されます。エラーの意味は理解できましたが、XML ファイルの操作方法がわかりません。この問題にどのようにアプローチすればよいですか?コードをステップ実行すると、myNode.Value = sql_connection; で停止します。null 値を返していると表示されますが、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>