How to Extract Selected Content Between Nodes in a Document

Extract Content Overview and Code

A common requirement when working with documents is to easily extract specific content from a range within the document. This content can consist of complex features such as paragraphs, tables, images etc. Regardless of what content needs to extracted, the method in which to extract this content will always be determined by which nodes are chosen to extract content between. These could be entire bodies of text or simple runs of text. There are many possible situations and therefore many different node types to consider when extracting content. For instance, you may want to extract content between:

  • Two specific paragraphs in the document.
  • Specific runs of text.
  • Different types of fields, e.g, merge fields.
  • Between the start and end ranges of a bookmark or comment.
  • Different bodies of the text contained in separate sections.

In some situations, you may even want to combine the different types of, for example, extract content between a paragraph and field, or between a run and a bookmark.

Often the goal of extracting this content is to duplicate or save it separately into a new document. For example, you may wish to extract the content and:

  • Copy it to a separate document.
  • Rendered a specific portion of a document to PDF or an image.
  • Duplicate the content in the document many times.
  • Work with this content separate from the rest of the document.

This is easy to achieve using Aspose.Words and the code implementation below. This article provides the full code implementation to achieve this along with samples of common scenarios using this method. These samples are just a few demonstrations of the many possibilities that this method can be used for. Some day this functionality will be a part of the public API and the extra code here will not be required. Feel free to post your requests regarding this functionality on the Aspose.Words forum here.

The Solution

The code in this section addresses all of the possible situations above with one generalized and reusable method. The general outline of this technique involves:

  1. Gathering the nodes which dictate the area of content that will be extracted from your document. Retrieving these nodes is handled by the user in their code, based on what they want to be extracted.
  2. Passing these nodes to the ExtractContent method which is provided below. You must also pass a boolean parameter which states if these nodes that act as markers should be included in the extraction or not.
  3. The method will return a list of cloned (copied nodes) of the content specified to be extracted. You can now use this in any way applicable, for example, creating a new document containing only the selected content.

The Code

To extract the content from your document you need to call the ExtractContent method below and pass the appropriate parameters. The underlying basis of this method involves finding block-level nodes (paragraphs and tables) and cloning them to create identical copies. If the marker nodes passed are block-level then the method is able to simply copy the content on that level and add it to the array.

However, if the marker nodes are inline (a child of a paragraph) then the situation becomes more complex, as it is necessary to split the paragraph at the inline node, be it a run, bookmark fields etc. Content in the cloned parent nodes not present between the markers is removed. This process is used to ensure that the inline nodes will still retain the formatting of the parent paragraph. The method will also run checks on the nodes passed as parameters and throws an exception if either node is invalid. The parameters to be passed to this method are:

  1. StartNode and EndNode: The first two parameters are the nodes which define where the extraction of the content is to begin and to end at respectively. These nodes can be both block-level (Paragraph, Table ) or inline-level (e.g Run, FieldStart, BookmarkStart etc.).
    1. To pass a field you should pass the corresponding FieldStart object.
    2. To pass bookmarks, the BookmarkStart and BookmarkEnd nodes should be passed.
    3. To pass comments, the CommentRangeStart and CommentRangeEnd nodes should be used.
  2. IsInclusive:

Defines if the markers are included in the extraction or not. If this option is set to false and the same node or consecutive nodes are passed, then an empty list will be returned.

  1. If a FieldStart node is passed then this option defines if the whole field is to be included or excluded.
  2. If a BookmarkStart or BookmarkEnd node is passed, this option defines if the bookmark is included or just the content between the bookmark range.
  3. If a CommentRangeStart or CommentRangeEnd node is passed, this option defines if the comment itself is to be included or just the content in the comment range.

The implementation of the ExtractContent method is found below. This method will be referred to in the scenarios in this article. The following method extracts blocks of content from a document between specified nodes.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
std::vector<System::SharedPtr<Node>> ExtractContent(System::SharedPtr<Node> startNode, System::SharedPtr<Node> endNode, bool isInclusive)
{
// First check that the nodes passed to this method are valid for use.
VerifyParameterNodes(startNode, endNode);
// Create a list to store the extracted nodes.
std::vector<System::SharedPtr<Node>> nodes;
// If either marker is part of a comment then to include the comment itself we need to move the pointer
// forward to the Comment Node found after the CommentRangeEnd node.
if (endNode->get_NodeType() == NodeType::CommentRangeEnd && isInclusive)
{
System::SharedPtr<Node> node = FindNextNode(NodeType::Comment, endNode->get_NextSibling());
if (node != nullptr)
{
endNode = node;
}
}
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
System::SharedPtr<Node> originalStartNode = startNode;
System::SharedPtr<Node> originalEndNode = endNode;
// Extract content based on block level nodes (paragraphs and tables). Traverse through parent nodes to find them.
// We will split the content of first and last nodes depending if the marker nodes are inline
startNode = GetAncestorInBody(startNode);
endNode = GetAncestorInBody(endNode);
bool isExtracting = true;
bool isStartingNode = true;
bool isEndingNode = false;
// The current node we are extracting from the document.
System::SharedPtr<Node> currNode = startNode;
// Begin extracting content. Process all block level nodes and specifically split the first and last nodes when needed so paragraph formatting is retained.
// Method is little more complex than a regular extractor as we need to factor in extracting using inline nodes, fields, bookmarks etc as to make it really useful.
while (isExtracting)
{
// Clone the current node and its children to obtain a copy.
System::SharedPtr<Node> cloneNode = currNode->Clone(true);
isEndingNode = System::ObjectExt::Equals(currNode, endNode);
if (isStartingNode || isEndingNode)
{
// We need to process each marker separately so pass it off to a separate method instead.
// End should be processed at first to keep node indexes.
if (isEndingNode)
{
// !isStartingNode: don't add the node twice if the markers are the same node.
ProcessMarker(cloneNode, nodes, originalEndNode, currNode, isInclusive, false, !isStartingNode, false);
isExtracting = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isStartingNode)
{
ProcessMarker(cloneNode, nodes, originalStartNode, currNode, isInclusive, true, true, false);
isStartingNode = false;
}
}
else
{
nodes.push_back(cloneNode);
}
// Move to the next node and extract it. If next node is null that means the rest of the content is found in a different section.
if (currNode->get_NextSibling() == nullptr && isExtracting)
{
// Move to the next section.
System::SharedPtr<Section> nextSection = System::DynamicCast<Section>(currNode->GetAncestor(NodeType::Section)->get_NextSibling());
currNode = nextSection->get_Body()->get_FirstChild();
}
else
{
// Move to the next node in the body.
currNode = currNode->get_NextSibling();
}
}
// For compatibility with mode with inline bookmarks, add the next paragraph (empty).
if (isInclusive && originalEndNode == endNode && !originalEndNode->get_IsComposite())
{
IncludeNextParagraph(endNode, nodes);
}
// Return the nodes between the node markers.
return nodes;
}

We will also define a custom method to easily generate a document from extracted nodes. This method is used in many of the scenarios below and simply creates a new document and imports the extracted content into it. The following method takes a list of nodes and inserts them into a new document.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> GenerateDocument(const System::SharedPtr<Document>& srcDoc, const std::vector<System::SharedPtr<Node>>& nodes)
{
// Create a blank document.
System::SharedPtr<Document> dstDoc = System::MakeObject<Document>();
// Remove the first paragraph from the empty document.
dstDoc->get_FirstSection()->get_Body()->RemoveAllChildren();
// Import each node from the list into the new document. Keep the original formatting of the node.
System::SharedPtr<NodeImporter> importer = System::MakeObject<NodeImporter>(srcDoc, dstDoc, ImportFormatMode::KeepSourceFormatting);
for (System::SharedPtr<Node> node : nodes)
{
System::SharedPtr<Node> importNode = importer->ImportNode(node, true);
dstDoc->get_FirstSection()->get_Body()->AppendChild(importNode);
}
// Return the generated document.
return dstDoc;
}

These helper methods below are internally called by the main extraction method. They are required, however as they are not directly called by the user, it is not necessary to discuss them further. The following helper methods used by the ExtractContent method.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Node> GetAncestorInBody(System::SharedPtr<Node> startNode)
{
while (startNode->get_ParentNode()->get_NodeType() != NodeType::Body)
{
startNode = startNode->get_ParentNode();
}
return startNode;
}
std::vector<System::SharedPtr<Node>> FillSelfAndParents(System::SharedPtr<Node> node, System::SharedPtr<Node> tillNode)
{
std::vector<System::SharedPtr<Node>> dest;
System::SharedPtr<Node> currentNode = node;
while (currentNode != tillNode)
{
dest.push_back(currentNode);
currentNode = currentNode->get_ParentNode();
}
return dest;
}
void RemoveNodesOutsideOfRange(System::SharedPtr<Node> markerNode, bool isInclusive, bool isStartMarker)
{
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
System::SharedPtr<Node> nextNode = markerNode->get_ParentNode()->get_FirstChild();
while (isProcessing && nextNode != nullptr)
{
System::SharedPtr<Node> currentNode = nextNode;
isSkip = false;
if (System::ObjectExt::Equals(currentNode, markerNode))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
{
isRemoving = false;
}
}
else
{
isRemoving = true;
if (isInclusive)
{
isSkip = true;
}
}
}
nextNode = nextNode->get_NextSibling();
if (isRemoving && !isSkip)
{
currentNode->Remove();
}
}
}
void VerifyParameterNodes(const System::SharedPtr<Node>& startNode, const System::SharedPtr<Node>& endNode)
{
// The order in which these checks are done is important.
if (startNode == nullptr)
{
throw System::ArgumentException(u"Start node cannot be null");
}
if (endNode == nullptr)
{
throw System::ArgumentException(u"End node cannot be null");
}
if (!System::ObjectExt::Equals(startNode->get_Document(), endNode->get_Document()))
{
throw System::ArgumentException(u"Start node and end node must belong to the same document");
}
if (startNode->GetAncestor(NodeType::Body) == nullptr || endNode->GetAncestor(NodeType::Body) == nullptr)
{
throw System::ArgumentException(u"Start node and end node must be a child or descendant of a body");
}
// Check the end node is after the start node in the DOM tree
// First check if they are in different sections, then if they're not check their position in the body of the same section they are in.
System::SharedPtr<Section> startSection = System::DynamicCast<Section>(startNode->GetAncestor(NodeType::Section));
System::SharedPtr<Section> endSection = System::DynamicCast<Section>(endNode->GetAncestor(NodeType::Section));
int32_t startIndex = startSection->get_ParentNode()->IndexOf(startSection);
int32_t endIndex = endSection->get_ParentNode()->IndexOf(endSection);
if (startIndex == endIndex)
{
if (startSection->get_Body()->IndexOf(GetAncestorInBody(startNode)) > endSection->get_Body()->IndexOf(GetAncestorInBody(endNode)))
{
throw System::ArgumentException(u"The end node must be after the start node in the body");
}
}
else if (startIndex > endIndex)
{
throw System::ArgumentException(u"The section of end node must be after the section start node");
}
}
System::SharedPtr<Node> FindNextNode(NodeType nodeType, System::SharedPtr<Node> fromNode)
{
if (fromNode == nullptr || fromNode->get_NodeType() == nodeType)
{
return fromNode;
}
if (fromNode->get_IsComposite())
{
System::SharedPtr<Node> node = FindNextNode(nodeType, (System::DynamicCast<CompositeNode>(fromNode))->get_FirstChild());
if (node != nullptr)
{
return node;
}
}
return FindNextNode(nodeType, fromNode->get_NextSibling());
}
void ProcessMarker(System::SharedPtr<Node> cloneNode,
std::vector<System::SharedPtr<Node>> &nodes,
System::SharedPtr<Node> node,
System::SharedPtr<Node> blockLevelAncestor,
bool isInclusive,
bool isStartMarker,
bool canAdd,
bool forceAdd)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (node == blockLevelAncestor)
{
if (canAdd && isInclusive)
{
nodes.push_back(cloneNode);
}
return;
}
// cloneNode is a clone of blockLevelNode. If node != blockLevelNode, blockLevelAncestor is ancestor of node; that means it is a composite node.
System::Diagnostics::Debug::Assert(cloneNode->get_IsComposite());
// If a marker is a FieldStart node check if it's to be included or not.
// We assume for simplicity that the FieldStart and FieldEnd appear in the same paragraph.
if (node->get_NodeType() == NodeType::FieldStart)
{
// If the marker is a start node and is not be included then skip to the end of the field.
// If the marker is an end node and it is to be included then move to the end field so the field will not be removed.
if ((isStartMarker && !isInclusive) || (!isStartMarker && isInclusive))
{
while (node->get_NextSibling() != nullptr && node->get_NodeType() != NodeType::FieldEnd)
{
node = node->get_NextSibling();
}
}
}
// Support a case if marker node is on the third level of document body or lower.
std::vector<System::SharedPtr<Node>> nodeBranch(FillSelfAndParents(node, blockLevelAncestor));
// Process the corresponding node in our cloned node by index.
System::SharedPtr<Node> currentCloneNode = cloneNode;
for (int index = nodeBranch.size() - 1; index >= 0; --index)
{
System::SharedPtr<Node> currentNode = nodeBranch.at(index);
int32_t nodeIndex = currentNode->get_ParentNode()->IndexOf(currentNode);
currentCloneNode = (System::DynamicCast<CompositeNode>(currentCloneNode))->get_ChildNodes()->idx_get(nodeIndex);
RemoveNodesOutsideOfRange(currentCloneNode, isInclusive || (index > 0), isStartMarker);
}
// After processing the composite node may become empty. If it has don't include it.
if (canAdd && (forceAdd || (System::DynamicCast<CompositeNode>(cloneNode))->get_HasChildNodes()))
{
nodes.push_back(cloneNode);
}
}
void IncludeNextParagraph(System::SharedPtr<Node> node, std::vector<System::SharedPtr<Node>> &nodes)
{
System::SharedPtr<Paragraph> paragraph = System::DynamicCast<Paragraph>(FindNextNode(NodeType::Paragraph, node->get_NextSibling()));
if (paragraph != nullptr)
{
// Move to first child to include paragraph without contents.
System::SharedPtr<Node> markerNode = paragraph->get_HasChildNodes() ? paragraph->get_FirstChild() : paragraph;
System::SharedPtr<Node> rootNode = GetAncestorInBody(paragraph);
ProcessMarker(rootNode->Clone(true), nodes, markerNode, rootNode, markerNode == paragraph, false, true, true);
}
}

Extract Content Between Paragraphs

This demonstrates how to use the method above to extract content between specific paragraphs. In this case, we want to extract the body of the letter found in the first half of the document. We can tell that this is between the 7th and 11th paragraphs. The code below accomplishes this task. The appropriate paragraphs are extracted using the CompositeNode.GetChild method on the document and passing the specified indices. We then pass these nodes to the ExtractContent method and state that these are to be included in the extraction. This method will return the copied content between these nodes which are then inserted into a new document. The below example shows how to extract the content between specific paragraphs using the ExtractContent method above. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Gather the nodes. The GetChild method uses 0-based index
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 6, true));
System::SharedPtr<Paragraph> endPara = System::DynamicCast<Paragraph>(doc->get_FirstSection()->get_Body()->GetChild(NodeType::Paragraph, 10, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = outputDataDir + u"ExtractContentBetweenParagraphs.doc";
dstDoc->Save(outputPath);

Extract Content Between Different Types of Nodes

We can extract content between any combinations of block-level or inline nodes. In this scenario below we will extract the content between the first paragraph and the table in the second section inclusively. We get the markers nodes by calling Body.FirstParagraph and CompositeNode.GetChild method on the second section of the document to retrieve the appropriate Paragraph and Table nodes. For a slight variation let’s instead duplicate the content and insert it below the original. The code example given below shows how to extract the content between a paragraph and table using the ExtractContent method. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Paragraph> startPara = System::DynamicCast<Paragraph>(doc->get_LastSection()->GetChild(NodeType::Paragraph, 2, true));
System::SharedPtr<Table> endTable = System::DynamicCast<Table>(doc->get_LastSection()->GetChild(NodeType::Table, 0, true));
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara, endTable, true);
// Lets reverse the array to make inserting the content back into the document easier.
for (auto it = extractedNodes.rbegin(); it != extractedNodes.rend(); ++it)
{
endTable->get_ParentNode()->InsertAfter(*it, endTable);
}
System::String outputPath = outputDataDir + u"ExtractContentBetweenBlockLevelNodes.doc";
// Save the generated document to disk.
doc->Save(outputPath);

Extract Content Between Paragraphs Based on Style

You may need to extract the content between paragraphs of the same or different styles, such as between paragraphs marked with heading styles. The code below shows how to achieve this. It is a simple example which will extract the content between the first instance of the “Heading 1” and “Header 3” styles without extracting the headings as well. To do this we set the last parameter to false, which specifies that the marker nodes should not be included.

In a proper implementation, this should be run in a loop to extract content between all paragraphs of these styles from the document. The extracted content is copied into a new document. The code example given below shows how to extract content between paragraphs with specific styles using the ExtractContent method. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Gather a list of the paragraphs using the respective heading styles.
TParagraphPtrVector parasStyleHeading1 = ParagraphsByStyleName(doc, u"Heading 1");
TParagraphPtrVector parasStyleHeading3 = ParagraphsByStyleName(doc, u"Heading 3");
// Use the first instance of the paragraphs with those styles.
System::SharedPtr<Node> startPara1 = parasStyleHeading1[0];
System::SharedPtr<Node> endPara1 = parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodes);
System::String outputPath = outputDataDir + u"ExtractContentBetweenParagraphStyles.doc";
dstDoc->Save(outputPath);

Extract Content Between Specific Runs

You can extract content between inline nodes such as a Run as well. Runs from different paragraphs can be passed as markers. The code below shows how to extract specific text in-between the same Paragraph node. The below example shows how to extract content between specific runs of the same paragraph using the ExtractContent method. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// Retrieve a paragraph from the first section.
System::SharedPtr<Paragraph> para = System::DynamicCast<Paragraph>(doc->GetChild(NodeType::Paragraph, 7, true));
// Use some runs for extraction.
System::SharedPtr<Run> startRun = para->get_Runs()->idx_get(1);
System::SharedPtr<Run> endRun = para->get_Runs()->idx_get(4);
// Extract the content between these nodes in the document. Include these markers in the extraction.
std::vector<System::SharedPtr<Node>> extractedNodes = ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
System::SharedPtr<Node> node = extractedNodes[0];
// Print the text of this node to the console.
std::cout << node->ToString(SaveFormat::Text).ToUtf8String() << std::endl;

Extract Content from a Bookmark

In a document, the content that is defined within a bookmark is encapsulated by the BookmarkStart and BookmarkEnd nodes. The content found between these two nodes make up the bookmark. You can pass either of these nodes as any marker, even ones from different bookmarks, as long as the starting marker appears before the ending marker in the document. We will extract this content into a new document using the code below. The IsInclusive parameter option shows how to retain or discard the bookmark. The below example shows how to extract the content referenced a bookmark using the ExtractContent method. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
System::SharedPtr<Section> section = doc->get_Sections()->idx_get(0);
section->get_PageSetup()->set_LeftMargin(70.85);
// Retrieve the bookmark from the document.
System::SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark1");
// We use the BookmarkStart and BookmarkEnd nodes as markers.
System::SharedPtr<BookmarkStart> bookmarkStart = bookmark->get_BookmarkStart();
System::SharedPtr<BookmarkEnd> bookmarkEnd = bookmark->get_BookmarkEnd();
// Firstly extract the content between these nodes including the bookmark.
TNodePtrVector extractedNodesInclusive = ExtractContent(bookmarkStart, bookmarkEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = outputDataDir + u"ExtractContentBetweenBookmark.Inclusive.doc";
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes this time without including the bookmark.
TNodePtrVector extractedNodesExclusive = ExtractContent(bookmarkStart, bookmarkEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = outputDataDir + u"ExtractContentBetweenBookmark.Exclusive.doc";
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << std::endl;

Extract Content from a Comment

A comment is made up of the CommentRangeStart, CommentRangeEnd and Comment nodes. All of these nodes are inline. The first two nodes encapsulate the content in the document which is referenced by the comment, as seen in the screenshot below. The Comment node itself is an InlineStory that can contain paragraphs and runs. It represents the message of the comment as seen as a comment bubble in the preview pane. As this node is inline and a descendant of a body you can also extract the content from inside this message as well.

The comment encapsulates the heading, first paragraph and the table in the second section. Let’s extract this comment into a new document. The IsInclusive option dictates if the comment itself is kept or discarded. The code to do this is below. You can download the template file of this example from here.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directories.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
System::String outputDataDir = GetOutputDataDir_WorkingWithDocument();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"TestFile.doc");
// This is a quick way of getting both comment nodes.
// Your code should have a proper method of retrieving each corresponding start and end node.
System::SharedPtr<CommentRangeStart> commentStart = System::DynamicCast<CommentRangeStart>(doc->GetChild(NodeType::CommentRangeStart, 0, true));
System::SharedPtr<CommentRangeEnd> commentEnd = System::DynamicCast<CommentRangeEnd>(doc->GetChild(NodeType::CommentRangeEnd, 0, true));
// Firstly extract the content between these nodes including the comment as well.
TNodePtrVector extractedNodesInclusive = ExtractContent(commentStart, commentEnd, true);
System::SharedPtr<Document> dstDoc = GenerateDocument(doc, extractedNodesInclusive);
System::String inclusiveOutputPath = outputDataDir + u"ExtractContentBetweenCommentRange.Inclusive.doc";
dstDoc->Save(inclusiveOutputPath);
std::cout << "File saved at " << inclusiveOutputPath.ToUtf8String() << std::endl;
// Secondly extract the content between these nodes without the comment.
TNodePtrVector extractedNodesExclusive = ExtractContent(commentStart, commentEnd, false);
dstDoc = GenerateDocument(doc, extractedNodesExclusive);
System::String exclusiveOutputPath = outputDataDir + u"ExtractContentBetweenCommentRange.Exclusive.doc";
dstDoc->Save(exclusiveOutputPath);
std::cout << "File saved at " << exclusiveOutputPath.ToUtf8String() << std::endl;

How to Extract Content using DocumentVisitor

Use the DocumentVisitor class to implement this usage scenario. This class corresponds to the well-known Visitor design pattern. With DocumentVisitor, you can define and execute custom operations that require enumeration over the document tree.

DocumentVisitor provides a set of VisitXXX methods that are invoked when a particular document element (node) is encountered. For example, DocumentVisitor.VisitParagraphStart is called when the beginning of a text paragraph is found and DocumentVisitor.VisitParagraphEnd is called when the end of a text paragraph is found. Each DocumentVisitor.VisitXXX method accepts the corresponding object that it encounters so you can use it as needed (say retrieve the formatting), e.g. both DocumentVisitor.VisitParagraphStart and DocumentVisitor.VisitParagraphEnd accepts a Paragraph object.

Each DocumentVisitor.VisitXXX method returns a VisitorAction value that controls the enumeration of nodes. You can request either to continue the enumeration, skip the current node (but continue the enumeration), or stop the enumeration of nodes.

These are the steps you should follow to programmatically determine and extract various parts of a document:

  • Create a class derived from DocumentVisitor.
  • Override and provide implementations for some or all of the DocumentVisitor.VisitXXX methods to perform some custom operations.
  • Call Node.Accept on the node from where you want to start the enumeration. For example, if you want to enumerate the whole document, use Document.Accept.

DocumentVisitor provides default implementations for all of the DocumentVisitor.VisitXXX methods. This makes it easier to create new document visitors as only the methods required for the particular visitor need to be overridden. It is not necessary to override all of the visitor methods.

This example shows how to use the Visitor pattern to add new operations to the Aspose.Words object model. In this case, we create a simple document converter into a text format.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithDocument();
// Open the document we want to convert.
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Visitor.ToText.doc");
// Create an object that inherits from the DocumentVisitor class.
System::SharedPtr<MyDocToTxtWriter> myConverter = System::MakeObject<MyDocToTxtWriter>();
// This is the well known Visitor pattern. Get the model to accept a visitor.
// The model will iterate through itself by calling the corresponding methods
// On the visitor object (this is called visiting).
// Note that every node in the object model has the Accept method so the visiting
// Can be executed not only for the whole document, but for any node in the document.
doc->Accept(myConverter);
// Once the visiting is complete, we can retrieve the result of the operation,
// That in this example, has accumulated in the visitor.
std::cout << myConverter->GetText().ToUtf8String() << std::endl;

You can download the template file of this example from here.

How to Extract Text Only

The ways to retrieve text from the document are:

  • Use Document.Save with SaveFormat.Text to save as plain text into a file or stream.
  • Use Node.ToString and pass the SaveFormat.Text parameter. Internally, this invokes save as text into a memory stream and returns the resulting string.
  • Use Node.GetText to retrieve text with all Microsoft Word control characters including field codes.
  • Implement a custom DocumentVisitor to perform customized extraction.

Using Node.GetText and Node.ToString

A Word document can contain control characters that designate special elements such as field, end of the cell, end of section etc. The full list of possible Word control characters is defined in the ControlChar class. The Node.GetText method returns text with all of the control character characters present in the node. Calling ToString returns the plain text representation of the document only without control characters. For further information on exporting as plain text see Using SaveFormat.Text. The below example shows the difference between calling the GetText and ToString methods on a node.

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
System::SharedPtr<Document> doc = System::MakeObject<Document>();
// Enter a dummy field into the document.
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->InsertField(u"MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
std::cout << "GetText() Result: " << doc->GetText().ToUtf8String() << std::endl;
// ToString will export the node to the specified format. When converted to text it will not retrieve fields code
// Or special characters, but will still contain some natural formatting characters such as paragraph markers etc.
// This is the same as "viewing" the document as if it was opened in a text editor.
std::cout << "ToString() Result: " << doc->ToString(SaveFormat::Text).ToUtf8String() << std::endl;