Sitecoore 9: I need to create a LinkField from a general link's xml


id="id" />

But I can only create a link field based on an id which I don't have without parsing this xml string.

How can I create a LinkField from this xml? Ultimately, Im trying to get the url for this General Link and I only have access to the xml

  • When you say "I only have access to the xml", are you retrieving this via the Sitecore API only some other way (static string from somewhere)? Without running this through the API, you cannot get URL from ID alone (since you also need to figure out the parents at minimum) – jammykam Mar 16 '18 at 0:40
  • The xml originates from a custom built Sitecore ORM but not sure the relevance of this. Given the link xml, I want to get the url - I assume the easiest way to do those would be by creating a LinkField object.. – Steve Ward Mar 16 '18 at 3:30
  • 2
    The relevance being I'm trying to understand whether the code you are running has Sitecore context and access to the API or whether it's from non-Sitecore code. – jammykam Mar 16 '18 at 3:35

In theory you can extend LinkUrl class and pass the xml instead of the LinkField object like that:

using System.Xml;
using Sitecore.Data;
using Sitecore.Xml.Xsl;

namespace My.Assembly.Namespace
    public class ExtendedLinkUrl : LinkUrl
        public string GetUrl(string linkFieldXml, Database database)
            if (string.IsNullOrEmpty(linkFieldXml) || database == null)
                return null;

            var xmlDocument = new XmlDocument();
            var linkElement = xmlDocument.DocumentElement;

            if (linkElement == null)
                return null;

            string linkType = linkElement.GetAttribute("linktype");
            string url = linkElement.GetAttribute("url");
            string id = linkElement.GetAttribute("id");
            string anchor = linkElement.GetAttribute("anchor");
            string queryString = linkElement.GetAttribute("querystring");

            if (!string.IsNullOrEmpty(anchor))
                anchor = "#" + anchor;

            switch (linkType)
                case "anchor":
                    return anchor;
                case "external":
                    return GetExternalUrl(url);
                case "internal":
                    return GetInternalUrl(database, url, id, anchor, queryString);
                case "javascript":
                    return GetJavaScriptUrl(url);
                case "mailto":
                    return GetMailToLink(url);
                case "media":
                    return GetMediaUrl(database, id);
                    return string.Empty;
  • Perfect. Thank you - seems to be working on first test .. – Steve Ward Mar 18 '18 at 23:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.