We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Unlink Table of Contents

Hi,

I have produced the following code to “unlink” a Table of Contents. Is there a better way to do it? Is it safe to use the magic string TOC \* MERGEFORMAT?

    foreach(Aspose.Words.Node node in doc.GetChildNodes(Aspose.Words.NodeType.FieldStart, true))
    {
        if (node.NextSibling.Range.Text == @" TOC  \* MERGEFORMAT ")
        {
            node.NextSibling.Remove();
            node.Remove();
        }
    }

Thanks, Jamie

Sorry, answered this myself, I can replace

node.NextSibling.Range.Text == @" TOC  \* MERGEFORMAT "

with

((Aspose.Words.Fields.FieldStart)node).FieldType == Aspose.Words.Fields.FieldType.FieldTOC

can’t I?

@JamieAspose

Thanks for your inquiry. You may use following code snippet, it will help you to accomplish the task.

foreach (Field field in doc.Range.Fields)
 {
    if (field.Type == FieldType.FieldTOC)
       field.Remove();     
 }

Thanks for your reply. I am using version 11.7, was Range.Fields after this version as I don’t seem to have it.

@JamieAspose

Thanks for your feedback. You are using a quite old version. It is recommended to use latest version of Aspose.Words, as we add all the fixes and enhancement in latest version of Aspose.Words. In your stated version, you can try following code snippet to remove the TOC Field.

Document doc = new Document("Remove-TC-Fields-Test.docx");
            
NodeCollection starts = doc.GetChildNodes(NodeType.FieldStart, true);
            
foreach (FieldStart start in starts)
{

    if (start.FieldType == FieldType.FieldTOC)
    {

        Node curNode = start;

        while (!(curNode.NodeType == NodeType.FieldEnd && ((FieldEnd)curNode).FieldType == FieldType.FieldTOC))
        {
            curNode = curNode.NextPreOrder(start.Document);
        }

        RemoveSequence(start, curNode);
        start.Remove();
        curNode.Remove();
        break;
    }
}

doc.Save(@"out.docx");

...............................

public static void RemoveSequence(Node start, Node end)
{
    Node curNode = start.NextPreOrder(start.Document);

    while (curNode != null && !curNode.Equals(end))
    {

        //Move to next node
        Node nextNode = curNode.NextPreOrder(start.Document);
        //Check whether current contains end node
        if (curNode.IsComposite)
        {

            CompositeNode curComposite = (CompositeNode)curNode;
            if (!curComposite.GetChildNodes(NodeType.Any, true).Contains(end) &&!curComposite.GetChildNodes(NodeType.Any, true).Contains(start))
            {
                nextNode = curNode.NextSibling;
                curNode.Remove();
            }

        }

        else
        {
            curNode.Remove();

        }
                
        curNode = nextNode;

    }

}