Im currently developing a VSTO Word AddIn in C#. Some Properties that are coming from SharePoint are stored in a customXmlPart with this Namespace Uri: “http://schemas.microsoft.com/office/2006/metadata/properties”
I already managed to get and process all the properties and store them in a list. Now i want to update the value of a sinlge property. As i know so far, it is not possible to edit the customXMLPart because its readonly. So i delete the old Part and Add the updated part again.
This is my code at the moment:
public static bool UpdateContentTypeProperty(string propertyName, string propertyValue)
{
var doc = Globals.ThisAddIn.Application.ActiveDocument;
var customXMLParts = doc.CustomXMLParts.SelectByNamespace("http://schemas.microsoft.com/office/2006/metadata/properties");
var updateSuccessful = false;
if (customXMLParts.Count > 0)
{
var xmlDoc = new XmlDocument();
var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
nsmgr.AddNamespace("p", "http://schemas.microsoft.com/office/2006/metadata/properties");
nsmgr.AddNamespace("ns", "501d336e-520f-475f-a88e-1742c35e8566");
nsmgr.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
foreach (CustomXMLPart part in customXMLParts)
{
xmlDoc.LoadXml(part.XML);
var node = xmlDoc.SelectSingleNode("//p:properties/documentManagement/ns:" + propertyName, nsmgr);
if (node != null)
{
// Search for the nil attribute and remove it if it exists
var nilAttribute = node.Attributes["nil", nsmgr.LookupNamespace("xsi")];
if (nilAttribute != null)
{
node.Attributes.Remove(nilAttribute);
}
// Update the node's inner text if the property value is not null or whitespace
if (!string.IsNullOrWhiteSpace(propertyValue))
{
node.InnerText = propertyValue;
}
updateSuccessful = true;
var updatedXml = xmlDoc.OuterXml;
// Delete the old part
part.Delete();
// Add a new part with the updated XML
doc.CustomXMLParts.Add(updatedXml);
break; // Exit after updating the first matching property
}
}
}
return updateSuccessful;
}
When troubleshooting with breakpoints, the added xml file looks correct. But when I unzip the word file and look at the customXmlPart, there is always this xsi:nil=true attribute.
That’s why I added this line here node.Attributes.Remove(nilAttribute);
The xml document is edited correctly, I think Word automatically adds the attribute again. This leads to the fact that Word can no longer read the properties and they are no longer displayed in the Word app.
My question now is how do I edit such a property correctly so that Word is able to read it?