Sitecore XslHelper GetItem()

I am using the XslHelper from some C# code. I use the GetItem() function to get an item from a NodePathIterator.
But the GetItem() generates an error “SystemInvalidOperationException: Enumeration has not started. Call MoveNext()“. The following code will fail with that error:

public static string GetDisplayName(System.Xml.XPath.XPathNodeIterator iterator)
{
  Sitecore.Xml.Xsl.XslHelper helper = new Sitecore.Xml.Xsl.XslHelper();
  Item item = helper.GetItem(iterator);
  if (item.DisplayName != String.Empty)
    return item.DisplayName;
  return item.Name;
}

The solution is to call f.ex. the fld() function before GetItem. This will work:

public static string GetDisplayName(System.Xml.XPath.XPathNodeIterator iterator)
{
  Sitecore.Xml.Xsl.XslHelper helper = new Sitecore.Xml.Xsl.XslHelper();
  // Call fld(".") to aviod the Enumeration has not started error.
  helper.fld(".", iterator);
  Item item = helper.GetItem(iterator);
  if (item.DisplayName != String.Empty)
    return item.DisplayName;
  return item.Name;
}

Sitecore support suggested another fix, which I haven’t tried yet:

public static string GetDisplayName(System.Xml.XPath.XPathNodeIterator iterator)
{
  Item item = null;
  if (iterator.MoveNext())
  {
    string ID = iterator.Current.GetAttribute("id", string.Empty);
    if (ID != string.Empty)
    {
      item = Context.Database.Items[ID];
      if (item.DisplayName == String.Empty)
        item.Name;
    }
  }
  return item.DisplayName;
}
Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 6 and tagged , , . Bookmark the permalink.

One Response to Sitecore XslHelper GetItem()

  1. The workaround code looks somewhat weird, but basically you need to call the .MoveNext() before doing anything with the iterator, and make sure it returns true.

    if (!iterator.MoveNext()) {
    return string.Empty;
    }

    Item item = GetItem(iterator);
    return item.DisplayName;

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s