@peng_dai
Following code example shows how to unlink all fields including IF fields and keep the sections in the document. Hope this helps you.
Document doc = new Document(MyDir + "Before - Copy.docx");
foreach (Field field in doc.Range.Fields)
{
if (field.Type == FieldType.FieldIf)
continue;
else
field.Unlink();
}
foreach (Field field in doc.Range.Fields)
{
bool iscontainSection = isIFContainsSection(doc, field);
if (iscontainSection == false)
field.Unlink();
else
{
//Unlink if field that contains the section break.
ArrayList nodes = UnlinkIFfieldKeepingSection(doc, field);
foreach (Node n in nodes)
{
n.Remove();
}
}
}
doc.Save(MyDir + "output.docx");
private static ArrayList UnlinkIFfieldKeepingSection(Document doc, Field field)
{
Node node = field.Start;
Node end = field.End;
ArrayList nodes = new ArrayList();
while (node != end)
{
node = node.NextPreOrder(doc);
if (node == field.Separator)
{
break;
}
if (node.NodeType == NodeType.Section)
{
node = ((Section)node).Body.FirstChild;
}
if (node.NodeType == NodeType.Paragraph)
{
Paragraph paragraph = (Paragraph)node;
if (!paragraph.IsEndOfSection)
{
nodes.Add(node);
}
}
else
nodes.Add(node);
}
nodes.Add(field.Separator);
nodes.Add(field.End);
return nodes;
}
private static bool isIFContainsSection(Document doc, Field field)
{
Boolean iscontainSection = false;
if (field.Type == FieldType.FieldIf)
{
//Check if field contains the section break;
Node node = field.Start;
Node end = field.End;
while (node != end)
{
node = node.NextPreOrder(doc);
if (node.NodeType == NodeType.Paragraph)
{
Paragraph paragraph = (Paragraph)node;
if (paragraph.IsEndOfSection)
{
iscontainSection = true;
break;
}
}
}
}
return iscontainSection;
}