Reputation: 756
I am currently attempting to replace a certain string in an xml document. I am doing this through Visual Studio using C#. The exact string I want to replace is Data Source = some-host
to Data Source = local-host
. The string is located under an attribute to my Strings. However, the attribute connectionString
has many values under it.
<Strings>
<add name="Cimbrian.Data.ConnectionString" connectionString="Data Source=some-host;Integrated Security=false;pooling=true;Min Pool Size=5;Max Pool Size=400;Connection Timeout=5;"/>
I have managed to be able to select and replace the entire values for both name
and connectionString
however I want to be able to select JUST the Data Source = some-host
to replace.
After loading the document my code currently looks like this,
XmlNode ConnectNode = Incident.SelectSingleNode("//Strings");
XmlNode add1 = ConnectNode.FirstChild;
add1.Attributes[1].Value = "THIS REPLACES ALL OF CONNECTION STRING";
But as the string value suggests, it is replacing far more than I want it to. Any help would be appreciated. Apologies if that is slightly hard to follow.
EDIT - I forgot to mention that if possible I want to do this without searching for the specific string Data Source = some-host
due to the fact that the some-host part may change, and I still want to be able to edit the value without having to change my code.
Upvotes: 1
Views: 104
Reputation: 2072
If you know exactly what you would be replacing you could use the replace method:
string string2 = string1.Replace("x", "y");
This would find all instances of x and replace them with y in string1
EDIT:
Your specific code would look something like this:
add1.Attributes[1].Value = add1.Attributes[1].Value.Replace("Data Source = some-host","Data Source = local-host");
EDIT 2:
Okay based on your comment I would then split the string on the semi-colon and then iterate to find the DataSource string and modify it and then concatenate everything back together
Upvotes: 1
Reputation: 1502096
This has really nothing to do with XML - the fact that the value of the attribute is itself a semi-colon-separated list is irrelevant as far as XML is concerned. You'd have the same problem if you had the connection string on its own.
You can use SqlConnectionStringBuilder
to help though:
var builder = new SqlConnectionStringBuilder(currentConnectionString);
builder.DataSource = "some other host";
string newConnectionString = builder.ToString();
This means you don't need to rely on the current exact value of some-host
(and spacing) which you will do if you just use string.Replace
.
Upvotes: 2