ReplaceBetweenTags function with delegate to describe transformation

Posted by Michael Freidgeim on Geeks with Blogs See other posts from Geeks with Blogs or by Michael Freidgeim
Published on Sun, 15 Apr 2012 02:01:02 GMT Indexed on 2012/04/15 5:31 UTC
Read the original article Hit count: 475

Filed under:

I've created a function that allow to replace content between XML tags with data, that depend on original content within tag, in particular to MAsk credit card number.

The function uses MidBetween extension from My StringHelper class

 /// <summary>
///
/// </summary>
/// <param name="thisString"></param>
/// <param name="openTag"></param>
/// <param name="closeTag"></param>
/// <param name="transform"></param>
/// <returns></returns>
/// <example>
/// // mask <AccountNumber>XXXXX4488</AccountNumber>
///requestAsString  = requestAsString.ReplaceBetweenTags("<AccountNumber>", "</AccountNumber>", CreditCard.MaskedCardNumber);
///mask cvv
///requestAsString = requestAsString.ReplaceBetweenTags("<FieldName>CC::VerificationCode</FieldName><FieldValue>", "</FieldValue>", cvv=>"XXX");
/// </example>
public static string ReplaceBetweenTags(this string thisString, string openTag, string closeTag,
Func<string, string> transform)
{
//See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex
string sRet = thisString;
string between = thisString.MidBetween(openTag, closeTag, true);
if (!
String.IsNullOrEmpty(between))
sRet=thisString.Replace(openTag + between + closeTag, openTag + transform(between) + closeTag);
return sRet;
}
public static string ReplaceBetweenTags(this string thisString, string openTag, string closeTag, string newValue)
{
//See also http://stackoverflow.com/questions/1359412/c-sharp-remove-text-in-between-delimiters-in-a-string-regex
string sRet = thisString;
string between = thisString.MidBetween(openTag, closeTag, true);
if (!
String.IsNullOrEmpty(between))
sRet = thisString.Replace(openTag + between + closeTag, openTag + newValue + closeTag);
return sRet;
}

© Geeks with Blogs or respective owner