Not able to remove bookmarkend from paragraph node

I am inserting a clone of a paragraph just before the original paragraph in a document. I am locating the paragraph to clone by using bookmarks. When I insert the clone of the paragraph, it maintains the bookmarks, which I don’t want it to do. So, I am attempting to remove the bookmarkstart and bookmarkend nodes from the clone by iterating through the collection of child nodes of the paragraph. Though I am getting back the collection of nodes in that paragraph (bookmarkstart/end, runs), the foreach loop only iterates through the collection once for the bookmarkstart then exits, but not for the runs or the bookmarkend.

Paragraph newPara = (Paragraph) para.Clone(true);
NodeCollection nc = newPara.GetChildNodes(NodeType.Any, true);
foreach(Node n in nc)
{
    if (n.NodeType == NodeType.BookmarkStart || n.NodeType == NodeType.BookmarkEnd)
    {
        newPara.ChildNodes[n.ParentNode.IndexOf(n)].Remove();
    }
}

This message was posted using Aspose.Live 2 Forum

Hi

Thanks for your inquiry. The problem occurs because you remove an element from the collection you iterate through. To resolve this you can use Node array instead of NodeCollection. Here is the modified code:

Paragraph newPara = (Paragraph) para.Clone(true);
Node[] nc = newPara.GetChildNodes(NodeType.Any, true).ToArray();
foreach(Node n in nc)
{
    if (n.NodeType == NodeType.BookmarkStart || n.NodeType == NodeType.BookmarkEnd)
    {
        newPara.ChildNodes[n.ParentNode.IndexOf(n)].Remove();
    }
}

But I think, there is much easier way to achieve the same:

Paragraph newPara = (Paragraph) para.Clone(true);
newPara.Range.Bookmarks.Clear();

Best regards,

That is the direction I was headed as I waited for your response. I will give it a try. Thanks.

I switched to newPara.Range.Bookmarks.Clear(). However, I am still only seeing the Bookmarkstart being removed from the newPara object and the Bookmarkend is actually now disappearing from the paragraph I cloned.

Am I right in assuming that because there can only be one instance of a bookmark in a Word document with a given name, that it is extending the bookmark when it adds the cloned paragraph before the original paragraph? If so, would removing the bookmark from the original paragraph and then replacing the bookmarkstart and bookmarkend in the original paragraph after I have inserted the cloned paragraph(s), be the way to maintain the bookmark on the original paragraph, but not on the cloned paragraphs?

Hi there,
Thanks for your inquiry.
I managed to reproduce the behaviour on my side. To avoid this please insert the cloned paragraph into the DOM before calling Bookmarks.Clear.
Thanks,

That worked and was much cleaner than the workaround I had. Thank you.