Reputation: 436
I have some input string like
<Parameters><job>true</job><BeginDate>August2017</BeginDate><processed>true</processed></Parameters>
I have to extract BeginDate
value and replace it with actual datetime value. So output should look like
<Parameters><job>true</job><BeginDate>08/01/2017</BeginDate><processed>true</processed></Parameters>
I am able to find August2017
and replace it with actual date but I am having trouble replacing that to the original.
Match match = Regex.Match(customDate, @"<BeginDate>([A-Za-z0-9\-]+)\<\/BeginDate>", RegexOptions.IgnoreCase);
if (match.Success)
{
string key = match.Groups[1].Value;
var newDate = DateTime.ParseExact(key, "MMMMyyyy", System.Globalization.CultureInfo.InvariantCulture);
???? how to replace newDate back to original ????
}
Upvotes: 0
Views: 123
Reputation: 191
You could use the original format you expected in a replace.
customDate = customDate.Replace(newDate.ToString("MMMMyyyy"), newDate.ToString("MM/dd/yyyy"));
Consider another approach to what appears to be XML:
var xe = System.Xml.Linq.XElement.Parse(customDate);
if(DateTime.TryParseExact(xe.Element("BeginDate").Value, "MMMMyyyy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out var newDate))
{
xe.Element("BeginDate").Value = newDate.ToString("MM/dd/yyyy");
}
You can then get the string back using:
xe.ToString(System.Xml.Linq.SaveOptions.DisableFormatting)
Upvotes: 1
Reputation: 31194
var xDoc = XDocument.Parse(inputString);
var BeginDate = xDoc.Descendants("BeginDate").First();
BeginDate.Value = "08/08/2017";
var outputString = xDoc.ToString();
Upvotes: 1