Hello,
I need to remove content from Bookmark. And then I want to remove bookmark itself.
bookmark.Text = “” → doesn’t work for me well due to the point that it remove something outside the bookmark (by the way it worked good in 19.4 version, but started work different when I updated to recent version). It looks like it depends on document content. But I have cases when it doesn’t work properly.
So I want to replace bookmark.Text = “” with custom solution to get a workaround. But it’s not clear how to do that properly. I’ve tried solution I found here. And it doesn’t work well. It doesn’t clear everything in bookmark content. Probably it’s because these solutions are pretty old and it’s not a proper way for recent library version.
Thank’s in advance.
@vabrutski Could you please attach the problematic document and specify for which of bookmarks Bookmark.Text = ""
does not work properly? We will check the issue and provide you more information.
In general removing bookmark’s content is removing content between BookmarkStart
and BookmarkEnd
nodes of the bookmark. You can try suing the approach similar to the approach used to extract content of the bookmark described here:
https://docs.aspose.com/words/net/how-to-extract-selected-content-between-nodes-in-a-document/
Thanks. I can’t share exact example due to the confidential information. To share it I need to recreate it from scratch. But I don’t what exactly causes this issue.
Thanks. I will look at the link
@vabrutski Thank you for additional information. Also, Node.NextPreOrder and Node.PreviousPreOrder method might be useful for you to traverse nodes using the pre-order tree traversal algorithm and removing content between nodes, which are on different level of the tree.
DocumentExplorer demo also might be useful for analyzing document’s structure.
Thank you. I will look at DocumentExplorer.
Please can you give more info around about how Node.NextPreOrder can be useful in my case?
@vabrutski Please see the following code:
Document doc = new Document(@"C:\Temp\in.docx");
// Get bookmark
Bookmark bk = doc.Range.Bookmarks["test"];
// Get start node
Node startNode = bk.BookmarkStart;
// Get End node
Node endNode = bk.BookmarkEnd;
Node curNode = startNode.NextPreOrder(doc);
// Remove content of the bookmark
while (curNode != null)
{
if (curNode.Equals(bk.BookmarkEnd))
break;
// move to next node
Node nextNode = curNode.NextPreOrder(doc);
// Check whether current contains end node
if (curNode.IsComposite)
{
if (!(curNode as CompositeNode).GetChildNodes(NodeType.Any, false).Contains(endNode) &&
!(curNode as CompositeNode).GetChildNodes(NodeType.Any, false).Contains(startNode))
{
nextNode = curNode.NextSibling;
curNode.Remove();
}
}
else
curNode.Remove();
curNode = nextNode;
}
1 Like