Get Node or Node ID by URL

Posted on November 29th, 2009 by Rich

This article; as the title suggests, is a short article demonstrating how to retrieve a node via the URL of a page. This has probably been covered before numerious times, but this is as much a reference for myself.
Moving on, most of you will probably be saying, why not use:


Well, if you are using lightboxes to display content from a node, and want to use an property from the current node (not the lightbox node) within the lightbox, using Node.GetCurrent() will return the lightbox node.

The first (and most important) part is to get the URL. This can be done by using the Request.UrlReferrer.Segments collection. This collection removes the need to split the url as each element in the collection is part of the url.

Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];

Next we need to use this string to retrive our information

public static Int32 GetNodeIdFromUrl(String url)
    int nodeId = -1;
    string xpathUrl = url == "/" ? "home" : url;
    string xpath = String.Format("//node[@urlName='{0}']", xpathUrl);
    var node = GetXmlNodeByXPath(xpath);
    if (node != null && node.Count > 0)
        while (node.MoveNext())
            var currentnode = node.Current.GetAttribute("id", "");
            int.TryParse(currentnode, out nodeId);

    return nodeId;

private static XPathNodeIterator GetXmlNodeByXPath(string xpathQuery)
    XPathNavigator xp = content.Instance.XmlContent.CreateNavigator();
    if (xp != null) return xp.Select(xpathQuery);
    return null;

The GetNodeIdFromUrl function simply returns the nodeId of the node where the urlName parameter is equal to the url passed into the function.

Note: line 4. If the page referrer is the homepage/root, the final segment in the UrlReferrer is "/" whereas the homepage node's urlName (in my case) is "home". This simply ensures a nodeid is returned.

comments powered by Disqus