使用标准微软库写入XML文件
我正在尝试使用此函数将值写入XML文件。我保留sql_connection下的值,但是收到错误,“对象引用未设置为对象的实例”。我明白错误的含义,但我不知道如何使用XML文件。我应该如何处理这个问题?当我遍历代码时,它停在myNode.Value = sql_connection;它说我正在返回一个空值,但sql_connection看到我在我的管理页面上输入的值。提前致谢。使用标准微软库写入XML文件
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>
好像你想要做的事,如:
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(@"..\..\XMLFile1.xml");
XmlNode root = myXmlDocument.DocumentElement;
//We only want to change one connection.
//This could be removed if you just want the first connection, regardless of name.
var targetKey = "sqlConnection1";
//get the add element we want
XmlNode myNode = root.SelectSingleNode(string.Format("add[@Name = '{0}']", targetKey));
var sql_Connection = "some sql connection";
//set the value of the connectionString attribute to the value we want
myNode.Attributes["connectionString"].Value = sql_Connection;
myXmlDocument.Save(@"..\..\XMLFile2.xml");
谢谢杰拉德。我的错误给每个人不提供错误的线。 – 2013-04-10 01:46:37
你XPATH值不正确。
XmlNode myNode = root.SelectSingleNode("/connectionString");
在线以上myNode
为null,因为方法SelectSingleNode
返回如果没有匹配的节点发现匹配XPath查询或null,并且有一个包含XPATH没有节点第一XmlNode的。看起来你离开的地方在的ConnectionStrings的“S”一个错字(或认为你可以使用属性名称,比如元素[节点]名
在第二个例子中,XPATH需要解析到
"/ConnectionStrings/add[@connectionString='asdf']"
再次,它看起来像你的,而不是蜱(')在表达一个错字,你正在使用引号(“)。
如果你正在寻找增加element
的属性,然后你的XPATH表达式会/ConnectionStrings/add
然后你可以得到那个节点的属性,假设你给了我们X ML从根节点开始。你可能想看看这个tutorial
一旦你通过XmlNode
的空问题,你有另一个错字。
node.Attributes["ConnectionStrings"].Value = sql_Connection;
在属性名称上面的XML例子是connectionString
不ConnectionStrings
,所以你将需要更改上面的线。
node.Attributes["connectionString"].Value = sql_Connection;
node.Attributes["**ConnectionStrings**"].Value = sql_Connection;
应该是准确的外壳为XML。 Xml区分大小写
对我来说听起来像'myNode'为null,而不是'sql_Connection'。请显示您的示例xml,看起来像你的'.SelectSingleNode'没有返回任何东西。 – 2013-04-09 01:00:20
同意。太糟糕了,他没有包括发生错误的行。那我们就不用猜测了。 – 2013-04-09 01:11:28
您正在制作配置文件。你可以使用配置,配置部分e.t.c类来制作那些配置文件 – 2013-08-19 12:05:39