Example handling fields containing Component Links (.NET)
When Components contain Component Links, your Core Service code needs to navigate the data structure as demonstrated in the following example.
static void ComponentComponentLinksFields(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, false, null);
ItemFieldDefinitionData seeAlsoFieldDefinition = schemaFields.Fields.Single(f => f.Name == "SeeAlso");
if (seeAlsoFieldDefinition != null)
{
if (seeAlsoFieldDefinition is ComponentLinkFieldDefinitionData)
{
XDocument content = XDocument.Parse(firstComponent.Content);
XNamespace ns = schemaFields.NamespaceUri;
string linkedComponentUri = content.Root.Element(ns + "SeeAlso").Attribute("{http://www.w3.org/1999/xlink}href").Value;
Console.WriteLine("Linked Component Uri: {0}", linkedComponentUri);
}
else
{
Console.WriteLine("Field SeeAlso is not a component link field!");
}
}
else
{
Console.WriteLine("No field named SeeAlso found!");
}
}