Example handling embedded fields in a Component (.NET)
When Components contain embedded fields (fields grouped together in a single Component field), your Core Service code needs to navigate the data structure as demonstrated in the following example.
For example, a Component may contain an Address field that contains the embedded fields Street, HouseNumber, ZipCode, and Municipality.
static void ComponentEmbeddedFields(CoreServiceClient client)
{
// Define a filter to return only Components.
OrganizationalItemItemsFilterData componentFilter = new OrganizationalItemItemsFilterData
{
ItemTypes = new[] { ItemType.Component }
};
// Get the Publication identified by publicationURI;
const string publicationUri = "tcm:0-3-1";
PublicationData publication = (PublicationData)client.Read(publicationUri, null);
// Get the list of Components in the root Folder of the Publication;
XElement components = client.GetListXml(publication.RootFolder.IdRef, componentFilter);
string firstComponentUri = components.Elements().Select(component => component.Attribute("ID").Value).First();
// Get the Fields of the first Component in that list;
ComponentData firstComponent = (ComponentData)client.Read(firstComponentUri, null);
SchemaFieldsData schemaFields =
client.ReadSchemaFields(firstComponent.Schema.IdRef, true /* expand embedded fields */, null);
ItemFieldDefinitionData addressFieldDefinition = schemaFields.Fields.SingleOrDefault(f => f.Name == "Address");
if (addressFieldDefinition != null)
{
if (addressFieldDefinition is EmbeddedSchemaFieldDefinitionData)
{
XDocument content = XDocument.Parse(firstComponent.Content);
XNamespace ns = schemaFields.NamespaceUri;
Console.WriteLine("Address information");
// print out the subfields of the Address (e.g. Street, City, PostCode)
foreach (XElement addressInfo in content.Root.Element(ns + "Address").Elements())
{
Console.WriteLine("{0}: {1}", addressInfo.Name.LocalName, addressInfo.Value);
}
}
else
{
Console.WriteLine("Field Address is not an embedded field!");
}
}
else
{
Console.WriteLine("No field named Address found!");
}
}