supersophisticated supersophisticated - 28 days ago 6
C# Question

Replace a string in an XML string

I have a string that looks like this:

newNodeXML = "<item id="qDf73w8emTg" parent_id="weLPzE243de" type="suite">
<content>
<name>Three</name>
</content>
</item>"


In my [WebMethod], I am trying to replace the parent_ID (randomly generated during run-time) like this:

Regex myRegex = new Regex(@""" parent_id=""(.*?)"" type=""");
newNodeXML = myRegex.Replace(newNodeXML, "d43df2qT45");


Please NOTE that for example/demo sake I have used 'd43df2qT45' in the second line above. I will actually be generating that randomly too.

My problem here is that the result of this comes out to be.
I do not want this:

<item id="qDf73w8emTgd43df2qT45suite">
<content>
<name>Three</name>
</content>
</item>


Instead, this is what I want it to be:

<item id="qDf73w8emTg" parent_ID="d43df2qT45" type="suite">
<content>
<name>Three</name>
</content>
</item>


P.S. I have tried some examples/google searches and all I could find were examples that got me this far.

Answer

You can use parentheses to catch the part before and after the value, then use $1 and $2 to include them in the replacement:

Regex myRegex = new Regex(@"( parent_id="")[^""]+("")");
newNodeXML = myRegex.Replace(newNodeXML, "$1" + "d43df2qT45" + "$2");

You can also do it using just string operations:

int pos1 = newNodeXML.IndexOf(" parent_id=\"") + 12;
int pos2 = newNodeXML.IndexOf('"', pos1);
newNodeXML = newNodeXML.Substring(0, pos1) + "d43df2qT45" + newNodeXML.Substring(pos2);