Get Node or Node ID by URL

Hi guys
I know I haven't written any articles for a while, this is because I've changed jobs, moved house and been to the land down under for two weeks so I've been pretty busy!

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:

Node.GetCurrent();

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.
Cheers

Comments

 

There are no comments on this page. Be the first to make one!