While writing a custom import tool for a Tridion 2011 project using the core service I have come across an issue when trying to save a component.
The following code works fine when the field on the component has a value but when it does not I get an error.
Here's my code (error handling removed for brevity):
//component is a ComponentData object from Tridion
var doc = new XmlDocument();
doc.LoadXml(component.Content);
var namespaces = new XmlNamespaceManager(doc.NameTable);
namespaces.AddNamespace("ns", doc.DocumentElement.NamespaceURI);
//componentFromSpreadsheet has a dictionary of fields and values to update
foreach (var field in componentFromSpreadsheet.Fields)
{
XmlNode xmlNode = doc.SelectSingleNode("//ns:" + field.Key, namespaces);
if (xmlNode == null)
{
xmlNode = doc.CreateNode(XmlNodeType.Element, field.Key,
doc.DocumentElement.NamespaceURI);
doc.DocumentElement.AppendChild(xmlNode);
}
//Namespace any Html in the field
string fieldValue = HtmlTidy.Tidy(field.Value);
xmlNode.InnerXml = fieldValue;
}
component.Content = doc.OuterXml;
//This line throws a FaultException<CoreServiceException> with an
//XmlException from tridion
client.Save(component, null);
Here's the message from Tridion:
The element 'Content' in namespace 'uuid:09ed2feb-f7cb-4760-ba4c-b9ff4f45d025' has invalid child element 'summary' in namespace 'uuid:09ed2feb-f7cb-4760-ba4c-b9ff4f45d025'. List of possible elements expected: 'related_links' in namespace 'uuid:09ed2feb-f7cb-4760-ba4c-b9ff4f45d025'
I know summary is a valid field for the schema of this component.
It seems like the schema is strict and cares about the order of the fields within the Xml. Is there any way around this or another approach?
Unfortunately you will have to add all mandatory fields in the correct order. The schema does indeed define the elements as an ordered sequence. You could try iterating the fields of the schema, and then selecting them from the spreadsheet rather than the approach you are currently using.