I want to update the contents of an RTF field with the Core Service. In the process, I convert it to an XDocument and back - maybe it's not needed and causes the issue, not sure. I'm using XDocument to quickly find the field I need in the XML.
The result is that the RTF Design tab shows the HTML and in the source it is HTMLEncoded. I have no idea why.
Code:
private void UpdateComp()
{
// Load
string namespaceUri = TridionXmlHelper.GetNamespaceUri(component, client);
NameTable nt = new NameTable();
XmlNamespaceManager nsMgr = new XmlNamespaceManager(nt);
nsMgr.AddNamespace("tridion", namespaceUri);
XmlDocument compXml = new XmlDocument(nt);
compXml.LoadXml(content);
string fieldName = "body";
// Update RTF field
var xDoc = compXml.ToXDocument();
var compField = from p in xDoc.Descendants()
where p.Name.LocalName == fieldName
select p;
var body = compField.First();
var fieldXml = "<body xmlns=\"uuid:f06437fa-826d-4ef1-8214-ceed0847bf84\">This is a <strong xmlns=\"http://www.w3.org/1999/xhtml\">bold</strong> test</body>";
// replace some simple text and save
body.Value = fieldXml.Replace("test", "<em>test</em>");
// Save
compXml = xDoc.ToXmlDocument();
component.Content = compXml.InnerXml;
client.CheckOut(component.Id, true, new ReadOptions());
client.Save(component, new ReadOptions());
client.CheckIn(component.Id, true, "", new ReadOptions());
}
// from http://stackoverflow.com/questions/1508572/converting-xdocument-to-xmldocument-and-vice-versa
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
public static string GetNamespaceUri(ComponentData comp, CoreServiceClient client)
{
LinkToSchemaData schemaLink = comp.Schema as LinkToSchemaData;
SchemaData schema = client.Read(schemaLink.IdRef, new ReadOptions()) as SchemaData;
string namespaceUri = schema.NamespaceUri;
return namespaceUri;
}