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;
}
Advertisement

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.

1 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;

    Like

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.