I am trying to change the contents of one of the content controls inside Word file.
It works or not depending if the content control already had a value before.
If it is empty the new value is used, if it is not empty, the change is ignored.
I have also attached the sample project.
using Aspose.Words;
using Aspose.Words.Markup;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AsposeReMergeTest
{
class Program
{
const string ReMergeField1 = "(Document) Title";
//const string ReMergeField1 = "(Document) Reply deadl.";
const string ReMergeField1Value = "New Document Title";
const string ReMergeField2 = "(Case) Planned close";
const string ReMergeField2Value = "New Planned Close";
static void Main(string[] args)
{
try
{
Dictionary<string, string> reMergeFieldsData = new Dictionary<string, string>
{
{ ReMergeField1, ReMergeField1Value },
{ ReMergeField2, ReMergeField2Value }
};
//var document = new Document("TestAnnTemplate.dotm"); // works fine
var document = new Document("TestAnnPartially.docx"); // broken
document.UpdatePageLayout();
var modified = false;
foreach (var contentControl in document.GetChildNodes(NodeType.StructuredDocumentTag, true).OfType<StructuredDocumentTag>())
{
if (string.IsNullOrWhiteSpace(contentControl.Title) ||
!reMergeFieldsData.TryGetValue(contentControl.Title, out var value))
continue;
var runs = contentControl.GetChildNodes(NodeType.Run, isDeep: true).OfType<Run>().Select((run, index) => (run, index));
foreach (var (run, index) in runs)
{
run.Text = index == 0 ? value : ""; // this line is hit and I can see that Text has changed
}
modified = true;
}
if (!modified)
return;
document.UpdatePageLayout();
var stream = new MemoryStream();
document.Save(stream, SaveFormat.Docx);
File.WriteAllBytes("output.docx", stream.ToArray());
}
catch (Exception exception)
{
Console.Error.WriteLine(exception);
}
}
}
}
AsposeReMergeTest.zip (82.0 KB)