Five New Optimizely Certifications are Here! Validate your expertise and advance your career with our latest certification exams. Click here to find out more

Get anchor links from XhtmlString

Jon
Jon
Vote:
0

Hi,

Is there a recommended way to extract anchor tags from an XhtmlString. So for example, I have this body copy -

<h1>Page title</h1>
<h2><a id="sub-title-1"></a>Sub title 1</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus rutrum ornare lectus id porttitor. Proin varius augue ipsum, nec tincidunt arcu efficitur in</p>
<h2><a id="sub-title-2"></a>Sub title 2</h2>
<p>Proin varius augue ipsum, nec tincidunt arcu efficitur in</p>
<p><a href="/episerver/CMS/Content/who,,141614/?epieditmode=False">Page link</a></p>

And I can get the anchor name doing something like this but wonder if there's a better way to do this?

@{
    string Pattern = @"(<a id="")(.*)("">)";
    Regex rgx = new Regex(Pattern);

    foreach (Match match in rgx.Matches(Model.BodyCopy.ToHtmlString()))
    {
        <h1>
            @match.Groups[2].Value
        </h1>
    }
}

I notice that's it's possible to use .Fragments property on an XhtmlString but that only seems to give me a long continuous like so (split across two entries)

"<h1>Page title</h1>\n<h2><a id=\"sub-title-1\"></a>Sub title 1</h2>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus rutrum ornare lectus id porttitor. Proin varius augue ipsum, nec tincidunt arcu efficitur in</p>\n<h2><a id=\"sub-title-2\"></a>Sub title 2</h2>\n<p>Proin varius augue ipsum, nec tincidunt arcu efficitur in</p>\n<p><a href=\""

And a UrlFragment.

Fairly new to Episerver and would appreciate some advice. Thanks

#245948
Dec 22, 2020 15:41
Vote:
0

Hi Jon,

There is no out-of-box function for this but I think you can follow this-

https://dotnetcodr.com/2014/12/05/finding-all-href-values-in-a-html-string-with-c-net/

#245969
Dec 23, 2020 6:48
Jon
Vote:
0

Thanks for the reply Ravindra.

#245973
Dec 23, 2020 10:58
This topic was created over six months ago and has been resolved. If you have a similar question, please create a new topic and refer to this one.
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.