我有一个想要修改连接字符串的 XML 文档。如何执行 foreach 循环并在此示例中修改 LocalSqlServer 的值?
<connectionStrings>
<clear />
<add name="Localip" connectionString="Data Source=db01;Initial Catalog=TestA;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="LocalSqlServer" connectionString="Data Source=db02;Failover Partner=db01;Initial Catalog=TestB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="ServerAp" connectionString="Data Source=LAPTOP;Initial Catalog=testc;Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>
这是我尝试过的,但我真的只想修改值而不是整个内容。对于这个例子,我想改变:
<add name="LocalSqlServer" connectionString="Data Source=db02;Failover Partner=db01;Initial Catalog=TestB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
<add name="LocalSqlServer" connectionString="Data Source=db07;Failover Partner=db07;Initial Catalog=TestB;Integrated Security=True;"
providerName="System.Data.SqlClient" />
这是我尝试过的:
System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
xmlDocument.Load(@"C:\xml.xml");
XmlNodeList elemList = xmlDocument.GetElementsByTagName("connectionStrings");
for (int i = 0; i < elemList.Count; i++)
{
foreach (XmlNode chldNode in elemList[i].ChildNodes)
{
Console.WriteLine(chldNode.Name.ToString());
if (chldNode.Name.ToString() == "add")
{
foreach (XmlAttribute xmlAtt in chldNode.Attributes)
{
if (xmlAtt.Value == "LocalSqlServer")
{
xmlAtt.InnerXml = "MyNewValue";
xmlDocument.Save(@"C:\xml2.xml");
break;
}
}
}
}
}