Storing Hidden XML In Word
This is a followup post to hosting hidden XML with in a Word document. Thanks to Cyril Mathey for sharing his C# code with us in the Newsgroups.
public static void SetDocumentVariable(MSWord.Document wordDoc, string variableName, string variableValue) {
object varNameRef = variableName;
MSWord.Variable var = wordDoc.Variables.get_Item(ref varNameRef);
if (var != null) {
var.Value = variableValue;
} else {
object varValueRef = variableValue;
wordDoc.Variables.Add(variableName, ref varValueRef);
}
}
public static string GetDocumentVariable(MSWord.Document wordDoc, string varName) {
object varNameRef = varName;
MSWord.Variable var = wordDoc.Variables.get_Item(ref varNameRef);
// If variable does not exist, an invalid Variable object is returned, not null.
// Trying to access a property of the returned object throws a COMException.
if (var != null)
try { return var.Value; } catch { }
return null;
}