0

I want to capture a part of an XML string and replace a captured value with a new one.

I have the following code:

Regex regex = new Regex("<ns1:AcctId>(?<AcctId>.*?)</ns1:AcctId>");
Match match = regex.Match(Xml);

string AcctId = match.Groups["AcctId"].Value;

string IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);

newXml = Regex.Replace(oldXml, regex, IBANizedAcctId); //DOES NOT WORK!

So I want to capture the AcctId in the ns1:AcctId XML element. Then I want to replace this one with a new value by converting the BBAN to IBAN and replace the value. The first part works, but I do not know how to accomplish the last part (I did find an idea here, but I do not understand it).

I hope someone can help me out!

5
  • ok... for some reason it won't let me post my answer... :( Commented May 5, 2014 at 17:05
  • here are the 2 changes i made to your existing code: Match match = regex.Match(oldXml); -and- string newXml = oldXml.Replace(AcctId, IBANizedAcctId); Commented May 5, 2014 at 17:06
  • Cannot answer it either: but I found this solution thanks to this answer: I know that the last part should be: Xml = Regex.Replace(Xml, regexString, string.Format("$1{0}$3", IBANizedAcctId)); where the regexString has three capturing groups: string regexDestAcctIntString = "(<ns1:AcctId>)(?<AcctId>.*?)(</ns1:AcctId>)"; The $1 and $3 refer to respectively the first and third capturing group and replace the middle with the new value. 80% sure it works. Commented May 5, 2014 at 17:13
  • @MaxOvrdrv that is even more logical. :) Commented May 5, 2014 at 17:14
  • try it out... mine will work 100% as well, and across your entire Xml string. Not just the match. Up to you ;) Commented May 5, 2014 at 17:15

1 Answer 1

1
Regex regex = new Regex("<ns1:AcctId>(?<AcctId>.*?)</ns1:AcctId>");
Match match = regex.Match(oldXml);

string AcctId = match.Groups["AcctId"].Value;

string IBANizedAcctId = IBANHelper.ConvertBBANToIBAN(AcctId);

newXml = oldXml.Replace(AcctId, IBANizedAcctId); //should work...
Sign up to request clarification or add additional context in comments.

2 Comments

I want to capture all occurences of <ns1:AcctId> *** </ns1:AcctId>, and they can contain different numbers.
I accepted the answer since it does work! But my requirement now is a bit different. I made a new question for that one here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.