This post has been migrated from, we apologise if some of the images or content is missing

This post has been migrated, original date 02 Mar 2009. Sometimes you want to retrieve an item or collection of items using C# and then pass these items to an XSLT rendering. The advantage of this is that you get the processing power of C# with the simple layout and Sitecore XSLT controls of a rendering. To do this the following methods and extension methods should help. The interesting stuff, the code:
        public static XPathNodeIterator ToXml(this Item item)
            return ToXml(new Item[] { item });

        public static XPathNodeIterator ToXml(this Item[] items)
            return ConvertToXml(items);

        private static XPathNodeIterator ConvertToXml (Item [] items)
            var packet = new Packet("values", new string[0]);
            foreach (Item item  in items)
                XmlDocument doc = new XmlDocument();
            return GetChildIterator(packet);

        private static XPathNodeIterator GetChildIterator(Packet packet)
            XPathNavigator xpathNavigator = packet.XmlDocument.CreateNavigator();
            if (xpathNavigator == null)
                return null;
            return xpathNavigator.SelectChildren(XPathNodeType.Element);
Using the Packet class which exists in the Sitecore.Xml namespace we can load our item/items into it and then pass the whole lot back to the XSLT rendering by creating an XPathNodeIterator from the packet . The extension methods allow us to more easily call the method. To call the methods:
        public static XPathNodeIterator doQuery(string query)         {
          Item[] results = Sitecore.Context.Database.SelectItems(query);
      return results.ToXml();         }
        public static XPathNodeIterator doQuery(string query)
            Item result = Sitecore.Context.Database.SelectSingleItem(query);
            return result.ToXml();
Within our XSLT we can then use it like so:
    <xsl:variable select="eic:doQuery($query)" name="results" />
    <xsl:for-each select="$results">
        <sc:text field="Title" />
I can iterate over the items as I would normally and can call of the standard Sitecore XSLT controls