0

我有一个想要修改连接字符串的 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;
                        }
                    }
                }
            }
        }
4

2 回答 2

1
var xDoc = XDocument.Load(@"C:\xml.xml")
var node = xDoc.XPathSelectElement("//add[@name='LocalSqlServer']");
node.Attribute("connectionString").Value = "some value";

或史蒂夫B建议

var node = xDoc.XPathSelectElement("//connectionStrings/add[@name='LocalSqlServer']");
于 2012-11-06T15:40:43.577 回答
0

使用System.Xml.Linq

var xml = XDocument.Load(fileName);
var localSqlServer = xml.Descendants("connectionStrings").Elements("add").FirstOrDefault(o => o.Attribute("name").Value == "LocalSqlServer");
if (localSqlServer != null)
    localSqlServer.SetAttributeValue("connectionString", "Your New Connection String");
xml.Save(fileName);
于 2012-11-06T15:38:25.800 回答