Sun Sep 26, 2021 11:14 am
Hello,
Thanks for your feedback.
According to your needs, we recommend that you modify your template file like the attached file and refer to the following sample code for testing.
- Code: Select all
static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile(@"sample.docx");
Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();
keyValuePairs.Add("age", "0");
keyValuePairs.Add("gender", "male");
foreach (KeyValuePair<string, string> kvp in keyValuePairs)
{
DeleteContent(document, kvp.Key, kvp.Value);
}
document.SaveToFile("result.docx", FileFormat.Docx);
}
public static void DeleteContent(Document doc, string key, string value)
{
//Find the contents that contain the string "{%if [[key]]"
TextSelection[] textSelection = doc.FindAllString("{%if [[" + key + "]]", false, false);
if (textSelection != null)
{
for (int i = 0; i < textSelection.Length; i++)
{
//Find the index of the paragraph to which the string "{%if [[key]]" belongs
TextSelection textSelection1 = textSelection[i];
Paragraph ownerParagraph1 = textSelection1.GetAsOneRange().OwnerParagraph;
int ifIndex = ownerParagraph1.OwnerTextBody.ChildObjects.IndexOf(ownerParagraph1);
//Find the first index of the paragraph to which the string "{%endif [[key]]" belongs
TextSelection textSelection2 = doc.FindString("{%endif [[" + key + "]]", false, false);
Paragraph ownerParagraph2 = textSelection2.GetAsOneRange().OwnerParagraph;
int endIfIndex = ownerParagraph2.OwnerTextBody.ChildObjects.IndexOf(ownerParagraph2);
//Find the content contained in the second "[[]]" in the paragraph to which the string "{%if [[key]]" belongs
Match match = Regex.Matches(ownerParagraph1.Text, @"\[\[\w+\]\]")[1];
string val = match.Value.Replace("[[", "").Replace("]]", "");
//If the content consistent with "if[[key]]" can be found in the document, only the current "if" paragraph and the corresponding "endif" paragraph will be deleted
//Otherwise delete the current "if" paragraph and the corresponding "endif" paragraph and all the content between them
if (val.Equals(value))
{
ownerParagraph2.OwnerTextBody.ChildObjects.RemoveAt(endIfIndex);
ownerParagraph1.OwnerTextBody.ChildObjects.RemoveAt(ifIndex);
}
else
{
Body ownerTextBody = ownerParagraph2.OwnerTextBody;
for (int j = endIfIndex; j >= ifIndex; j--)
{
ownerTextBody.ChildObjects.RemoveAt(j);
}
}
}
}
}
If there are any other issues related to our products, just feel free to contact us.
Sincerely,
Brian
E-iceblue support team
Login to view the files attached to this post.