Valid for Sitecore
5.2, 5.3
What API code should I use to import data from external source?
Sitecore API provides a reliable and well controlled solution when it comes to content migration.
Here is some sample code that will help you investigate and manage Sitecore items using API:
- You can get items from any database using the following syntax: Database db = Sitecore.Configuration.Factory.GetDatabase("master");
Item item = db.Items["sitecore/content/home"]; -
Here is the way to extract field values:Response.Write(item.Fields["title"].Value+"<br/>");
Response.Write(item.Fields["text"].Value+"<br/>"); -
Use SecurityDisabler object to allow user to create (delete, rename) nodes:using (new SecurityDisabler())
{
Database db = Sitecore.Configuration.Factory.GetDatabase("master");
TemplateItem template = db.Templates["Document"];
Item child = db.Items["/sitecore/content/home"].Add("newItem1", template);
} -
Create an item from TemplateDatabase database = Factory.GetDatabase("master");
Item itmHome = database.Items["/sitecore/content/home"];
TemplateItem template = Factory.GetDatabase("master").Templates["Document"];
Item itm = itmHome.Add("ArchiveItemTest2",template); -
A note concerning item editing – you should edit the items in EditContext. It is a convenient wrapper over Item.BeginEdit() and Item.EndEdit().
The code below illustrates the idea:Sitecore.Context.SetActiveSite("shell");
Sitecore.Context.Domain.Login("admin","");
Item root = Sitecore.Context.ContentDatabase.Items["/sitecore/content/home"];
Item child = root.Add("autonode", root.Template);
using (new EditContext(child))
{
child.Fields["Title"].Value = "autotitle";
}
Sitecore.Context.Domain.Logout();