Tuesday, November 08, 2005

How to Retrieve XML data from MS Word form fields using VSTO.

MS word has this cool feature where you can attach an XML schema to the document and tag the form fields with XML elements in the schema. When you save the document as XML, the form field values are stored as XML data. Unfortunately saving XML data does not work with Check box and Drop down form fields. So, if you need to save the data from Check box and Drop down form fields you have to walk through all the XML nodes and retrive the data. Below is a C# code snippet to walk through the XML nodes and write it as XML.


private string BuildWordDocumentXmlData(XMLNode xmlNode)
{
object oRef = 1;
object missing = Missing.Value;
Range range;
StringBuilder xmlString = new StringBuilder();
xmlString.Append("");
if(!xmlNode.HasChildNodes)
{
xmlString.Append("<" + xmlNode.BaseName + ">");
range = xmlNode.Range;
if (range.FormFields.Count > 0)
{
FormField formField = range.FormFields.get_Item(ref oRef);
if (formField.Type == WdFieldType.wdFieldFormCheckBox)
{
if (formField.Result.CompareTo("1") == 0)
{
xmlString.Append("true");
}
else
{
xmlString.Append("false");
}
}
else if (formField.Type == WdFieldType.wdFieldFormTextInput)
{
if (formField.Result != null)
{
xmlString.Append(formField.Result);
}
}
}
else
{
xmlString.Append(xmlNode.Text);
}
xmlString.Append("");
}
else
{
string returnString;
xmlString.Append("<" + xmlNode.BaseName + ">\n");
foreach(XMLNode childXmlNode in xmlNode.ChildNodes)
{
returnString = BuildWordDocumentXmlData(childXmlNode);
xmlString.Append(returnString + "\n");
}
xmlString.Append("");
}
return xmlString.ToString();
}
public void SaveWordDocumentXmlData(string xmlFileName)
{
Application.ScreenUpdating = false;
string xml;
try
{
xml = BuildWordDocumentXmlData(ActiveDocument.XMLNodes[1]);
using (StreamWriter sw = new StreamWriter(xmlFileName))
{
sw.Write(xml);
}
}
catch(Exception exp)
{
Trace.WriteLine(exp.ToString());
}
Application.ScreenUpdating = true;
}

No comments: