BookmarkStart and BookmarkEnd contain section which should be outside

I have a word file which is in between two section breaks.

	SharedPtr<Section> TryGetSectionInBookmark(const SharedPtr<Document>& currentDocument, const SmartPtr<Bookmark>& bookmark)
	{
		SmartPtr bookmarkStart{ bookmark->get_BookmarkStart() };
		while (bookmarkStart != nullptr)
		{
			if (bookmarkStart->get_NodeType() == NodeType::BookmarkEnd)
			{
				break;
			}

			bookmarkStart = bookmarkStart->PreviousPreOrder(currentDocument);
			if (bookmarkStart->get_NodeType() != NodeType::Section)
			{
				continue;
			}

			return System::Cast<Section>(bookmarkStart);
		}

		return nullptr;
	}

This seems to return a section even if the bookmark doesn’t contain any section.

@lefev

It seems that your implementation is returning a section even when the bookmark does not contain any section. This could be due to the logic in your TryGetSectionInBookmark function, which traverses the nodes in a pre-order manner and checks for the NodeType::Section.

To ensure that you only return a section if it is indeed part of the bookmark, you might want to adjust your logic. Here’s a revised version of your function that checks if the bookmark’s start and end nodes are within the same section:

SharedPtr<Section> TryGetSectionInBookmark(const SharedPtr<Document>& currentDocument, const SmartPtr<Bookmark>& bookmark)
{
    SmartPtr bookmarkStart{ bookmark->get_BookmarkStart() };
    SmartPtr bookmarkEnd{ bookmark->get_BookmarkEnd() };

    // Ensure both bookmark start and end are not null
    if (bookmarkStart == nullptr || bookmarkEnd == nullptr)
    {
        return nullptr;
    }

    // Get the parent sections of the bookmark start and end
    SmartPtr<Node> startSection = bookmarkStart->get_ParentNode()->get_Ancestor(NodeType::Section);
    SmartPtr<Node> endSection = bookmarkEnd->get_ParentNode()->get_Ancestor(NodeType::Section);

    // Check if both bookmark start and end are in the same section
    if (startSection != nullptr && startSection == endSection)
    {
        return System::Cast<Section>(startSection);
    }

    return nullptr;
}

In this revised version, the function first checks if both the bookmark start and end nodes are valid. Then, it retrieves the parent sections of both nodes and compares them. If they belong to the same section, it returns that section; otherwise, it returns nullptr.

This should help ensure that you only get a section if the bookmark is indeed contained within it. If you continue to experience issues, consider debugging the node traversal to ensure that the correct nodes are being evaluated.

@lefev Bookmark does not contain sections at all, the section can contain bookmark start or bookmark end. Please see our documentation to learn more about Aspose.Words Document Object Model:
https://docs.aspose.com/words/cpp/aspose-words-document-object-model/

1 Like