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

Free Support Forum - aspose.com

Remove TOC markers from document

Dear Sir or Madam,


What would be the easiest way to remove all TOC markers from a document?

Thanks in advance,
Regards,
Alex

Hi Alex,


Thanks for your inquiry. Please note that TOC in Word document is actually represented by a field. Every field in the Word document starts from a FieldStart and ends with FieldEnd nodes. Therefore, to completely remove TOC from the document you should remove all content between these nodes. Could you please attach your input Word document here for testing? We will then provide you code to remove those markers.

Best regards,
Thank you for quick reply!
The document is attached. Just to double-check what I wasn't got wrong - I need to remove TOC markers (which are TC fields in Word)
Alex

Hi Alex,


Thanks for your inquiry. Please use the following code to remove TOC field from your document.

Document doc = new Document(MyDir
@“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(MyDir + @“out.docx”);


public static void RemoveSequence(Node start, Node end)<o:p></o:p>

{

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;

}

}


I hope, this helps.

Best regards,

Hi Awais


Thanky you, it helped!

Alex

Hi Alex,


Thanks for your feedback. Please let us know if we can be of any further assistance in future.

Best regards,