Tag Archives: urlfragment

Resolving links in XhtmlStrings, EPiServer 7.16.1

Did you ever try to store a XhtmlString in a variable and use it in your code? Maybe you noticed that some stuff, like links, isn’t very useful because they are internal.

I noticed this when i upgraded a site from CMS6, and on that site i had a working code that rendered dynamic content so the code i passed to my variable actually was useful, but it broke when i upgraded the site. What i did find than, was that XhtmlStrings are made up of Fragments. And that’s really useful!

One thing you can do with these fragments is resolving internal links, and this is because links are stored as a UrlFragment. A typical XhtmlString could look like:

As you can see, we have regular content, UrlFragments and a ContentFragment. So now, we can write some code to do stuff with different fragements:

StringBuilder sBuilder = new StringBuilder();
foreach (IStringFragment sFragment in Xhtml.Fragments)
{
  if (sFragment is ContentFragment)
  {
  }
  if (sFragment is UrlFragment)
  {
  }
  sBuilder.Append(sFragment.GetViewFormat());
}

Maybe you would like to do something with a block?

if (sFragment is ContentFragment)
{
  ContentFragment cFragment = sFragment as ContentFragment;
  var Content = Repository.Get<ContentData>(cFragment.ContentLink);
}

Or, if you would like to resolve links in your XhtmlString:

if(sFragment is UrlFragment) 
{
  UrlFragment uFragment = sFragment as UrlFragment;
  UrlBuilder uBuilder = new UrlBuilder(uFragment.InternalFormat);
  Global.UrlRewriteProvider.ConvertToExternal(uBuilder, null, Encoding.UTF8);
  sBuilder.Append(uBuilder.Uri);
  continue;
}

The complete code i use to resolve links before passing the content to a javascript:

public static string ParseXhtmlString(XhtmlString Xhtml)
{
    StringBuilder sBuilder = new StringBuilder();
    if (!(Xhtml == null || Xhtml.IsEmpty))
    {
        foreach (IStringFragment sFragment in Xhtml.Fragments)
        {
            UrlFragment uFragment = sFragment as UrlFragment;
            if(uFragment != null) 
            {
                try
                {
                    UrlBuilder uBuilder = new UrlBuilder(uFragment.InternalFormat);
                    Global.UrlRewriteProvider.ConvertToExternal(uBuilder, null, Encoding.UTF8);
                    sBuilder.Append(uBuilder.Uri);
                    continue;
                }
                catch (Exception)
                { }
            }
            sBuilder.Append(sFragment.GetViewFormat());
        }
    }
    return sBuilder.ToString();
}