user222427
user222427

Reputation:

C# how to foreach loop an XML document and modify a value

I have an XML document that I want to modify the connectionstrings to. How do I do a foreach loop and in this example modify the value of 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>

This is what I've tried, but I really just want to modify the value not the whole content. For this example I want to change:

<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" />

This is what I've tried:

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;
                        }
                    }
                }
            }
        }

Upvotes: 0

Views: 5378

Answers (2)

L.B
L.B

Reputation: 116108

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

or as SteveB suggested

var node = xDoc.XPathSelectElement("//connectionStrings/add[@name='LocalSqlServer']");

Upvotes: 1

Knaģis
Knaģis

Reputation: 21485

Using 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);

Upvotes: 0

Related Questions