Sunday 25 May 2014

Deserialize a content item programmatically in Sitecore

Leave a Comment
In my previous blog; I’ve explained how to serialize a content item using Sitecore API. In this blog I’ll show how to deserialize or restore content item programmatically in Sitecore. Below function RestoreItem(string itemPath) takes item path as input parameter and restore the item in content tree.
 public void RestoreItem(string itemPath)
            Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master");
            Sitecore.Data.Serialization.ItemReference itemReference = new Sitecore.Data.Serialization.ItemReference(masterDB.Name, itemPath);
            string path = Sitecore.Data.Serialization.PathUtils.GetFilePath(itemReference.ToString());

            Sitecore.Data.Serialization.LoadOptions options = new Sitecore.Data.Serialization.LoadOptions(masterDB);
            options.ForceUpdate = true;

            using (new Sitecore.SecurityModel.SecurityDisabler())
                Sitecore.Data.Serialization.Manager.LoadItem(path, options);               
Sitecore.Data.Serialization.Manager class is having all Serialization related operations. LoadItem(path, options) function restores only given item path in content tree. If you want to restore entire sub content tree from given item path then you have to use LoadTree(path, options) function.

Execution Steps:
  1. Serialize Sitecore content item. For example: Serialize /sitecore/content/Home/Demo News Article/item1 content item.
  2. Change any field value of that Sitecore content item. 
  3. Call function RestoreItem(string itemPath) with item path. For example:
    string path = "/sitecore/content/Home/Demo News Article/item1";
  4. Content item will restore in Sitecore content tree. All changes made in step 2 will be reverted.
Comments and suggestions are most welcome. Happy coding!


Post a Comment