Hello, I am working with WordprocessingDocument to be able to replace the fields that appear in a Word as ## USER ## and that I generate a document based on a template.
using (WordprocessingDocument doc = WordprocessingDocument.Open(dg.FileName, false, new OpenSettings()
{
}))
{
foreach (DocumentVariables docVars in doc.MainDocumentPart.DocumentSettingsPart.Settings.Descendants<DocumentVariables>().ToList())
foreach (DocumentVariable docVar in docVars)
{
Add(sb, docVar.Val);
}
foreach (HeaderPart docVars in doc.MainDocumentPart.HeaderParts)
{
foreach (Paragraph var in docVars.RootElement.Descendants<Paragraph>().ToList())
//foreach (Run varRun in var.Descendants<Run>())
// foreach (Text varText in var.Descendants<Text>())
// Add(sb, varText.Text);
Add(sb, var.InnerText);
}
foreach (Paragraph var in doc.MainDocumentPart.RootElement.Descendants<Paragraph>().ToList())
//foreach (Run varRun in var.Descendants<Run>())
// foreach (Text varText in var.Descendants<Text>())
// Add(sb, varText.Text);
Add(sb, var.InnerText);
}
The question is now, if I search in the InnerText fields, everything works perfectly (but that property can not be modified), so I read the "tags" perfectly.
On the other hand, if I want to replace them, I have to use the code I have commented on (use the Text property of the Text), but there are times when Word breaks the string and I can not find ## USER ## but sometimes I find ## and in the following node USER ## , which completely breaks the replacements.
How could I avoid this, by Word or by code?
Note: the Add function only adds to a list the found texts