Reputation: 85
I am trying to work on a regular expression to replace XML content in C# with no success.
Here is the sample code with XML example.
static void Main(string[] args)
{
Console.Write(ReplaceValue("<test val='123'><this>something</this></test>", "ANY_XML_BLOB", @"<test[^>]*>\s*(?'value'[^</test]*)"));
}
static string ReplaceValue(string request, string newFieldValue, string pat)
{
string value = String.Empty;
Regex conditionRex = new Regex(pat, RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match match = conditionRex.Match(request);
if(match.Success)
{
value = match.Groups["value"].Value;
return request.Replace(value, newFieldValue);
}
return request;
}
}
Expected output is "this" tag and all sub-contents be replaced by the word ANY_XML_BLOB.
Any help fixing this would be appreciated.
Thanks!
Upvotes: 1
Views: 3641
Reputation: 39017
While I would recommend following the XML parsing route, you COULD try this:
string output = Regex.Replace(input, "<this>.*?</this>", "ANY_XML_BLOB");
Upvotes: 2
Reputation: 2347
I would recommend using a proper XML parser for trying to do what you want to do. Using a regex is just asking for trouble. Something in the System.Xml namespace would suit you. You might even give LINQ to XML a try.
PsuedoCode:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("<test val='123'><this>something</this></test>");
XmlNodeList testelelist = xmlDoc.GetElementsByTagName("test");
XmlNode testele = testelelist.Item(0);
testele.InnerText = "ANY_XML_BLOB";
Upvotes: 2