This project has moved and is read-only. For the latest updates, please go here.

MergeField Replacement works, but not when parsing

Oct 23, 2012 at 8:14 PM
Edited Oct 23, 2012 at 8:16 PM

I'm currently rewriting a .NET 1.1 Interop to Word using OpenXML, and I currently have a working OpenXML MergeField replacement working with the following code.  The problem is that the merge field values contain tons of HTML Tables, <br/> etc tags.  Thus my desire to use this library.  However any time I try to use the library to append to the existing Run or Text element I get errors in validation (and there by when opening the mail merged document).  So what is the correct way in this regard to replace the content of the existing Text element with the parsed HTML from your library?

foreach (FieldCode field in docGenerated.MainDocumentPart.RootElement.Descendants<FieldCode>()) {
	var fieldNameStart = field.Text.LastIndexOf(FieldDelimeter, System.StringComparison.Ordinal);
          var fieldname = field.Text.Substring(fieldNameStart + FieldDelimeter.Length).Trim();

	// Get the value from my merge field
	var fieldValue = fm.Merge(fieldname);

 	foreach (Run run in docGenerated.MainDocumentPart.Document.Descendants<Run>()) {
          	var textFromRun = run.Descendants<Text>().Where(a => a.Text == "�" + fieldname + "�").ToList();

                   foreach (Text txt in textFromRun) {
                   		txt.Text = fieldValue;