there is an easy way to read through all the tags and extract the content
If you are ok with using ThirdParty library You can use the use theHtmlAgilityPacklike given below
sample code
var doc = new HtmlDocument();
doc.LoadHtml(@"example text here <mytag> hello </mytag> more text <mytag> goodbye </mytag> more text <mytag> back again </mytag> example text");
//Get all mytag nodes
HtmlNodeCollection col = doc.DocumentNode.SelectNodes("//mytag");
//Grab the content inside each node
foreach (HtmlNode node in col)
{
string data = node.InnerText;
}
Ensure that you have added the below namespace after add in the dll to your project
usingHtmlAgilityPack;
Another option is to use the Regex to extract the string in between of body tags like given below
// Populate the html string here from database
string html = @"example text here <mytag> hello </mytag> more text <mytag> goodbye </mytag> more text <mytag> back again </mytag> example text";
string theBody = string.Empty;
//Regex Options
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Singleline;
//Get the matching string
foreach (Match m in Regex.Matches(html, "<mytag>(.*?)</mytag>", options))
{
// Output your values here
Console.WriteLine(m.Groups[1].Value);
}
Member
140 Points
591 Posts
Extracting value between two string (multiple occurrences)
Aug 19, 2020 04:07 PM|RageRiot|LINK
Hi,
I have a string that can contain multiple occurrences of strings between start/end tags:
"example text here <mytag>hello</mytag> more text <mytag>goodbye</mytag> more text <mytag>back again</mytag> example text"
I'm sure there is an easy way to read through all the tags and extract the content, can anyone help?
Many thanks
All-Star
50841 Points
9895 Posts
Re: Extracting value between two string (multiple occurrences)
Aug 19, 2020 05:41 PM|A2H|LINK
If you are ok with using ThirdParty library You can use the use the HtmlAgilityPack like given below
sample code
Ensure that you have added the below namespace after add in the dll to your project
Another option is to use the Regex to extract the string in between of body tags like given below
Aje
My Blog | Dotnet Funda
Member
140 Points
591 Posts
Re: Extracting value between two string (multiple occurrences)
Aug 19, 2020 07:26 PM|RageRiot|LINK
Thank you A2H, I'll check out that library but the regex looks like it'll work well for this.