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, for example merge fields.
  • Between the start and end ranges of a bookmark or comment.
  • Different bodies of 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 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. Below method which 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-.NET
public static ArrayList ExtractContent(Node startNode, 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.
ArrayList nodes = new ArrayList();
// Keep a record of the original nodes passed to this method so we can split marker nodes if needed.
Node originalStartNode = startNode;
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
while (startNode.ParentNode.NodeType != NodeType.Body)
startNode = startNode.ParentNode;
while (endNode.ParentNode.NodeType != NodeType.Body)
endNode = endNode.ParentNode;
bool isExtracting = true;
bool isStartingNode = true;
bool isEndingNode = false;
// The current node we are extracting from the document.
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.
Node cloneNode = currNode.Clone(true);
isEndingNode = currNode.Equals(endNode);
if ((isStartingNode || isEndingNode) && cloneNode.IsComposite)
{
// We need to process each marker separately so pass it off to a separate method instead.
if (isStartingNode)
{
ProcessMarker((CompositeNode)cloneNode, nodes, originalStartNode, isInclusive, isStartingNode, isEndingNode);
isStartingNode = false;
}
// Conditional needs to be separate as the block level start and end markers maybe the same node.
if (isEndingNode)
{
ProcessMarker((CompositeNode)cloneNode, nodes, originalEndNode, isInclusive, isStartingNode, isEndingNode);
isExtracting = false;
}
}
else
// Node is not a start or end marker, simply add the copy to the list.
nodes.Add(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.NextSibling == null && isExtracting)
{
// Move to the next section.
Section nextSection = (Section)currNode.GetAncestor(NodeType.Section).NextSibling;
currNode = nextSection.Body.FirstChild;
}
else
{
// Move to the next node in the body.
currNode = currNode.NextSibling;
}
}
// 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. Below 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-.NET
public static Document GenerateDocument(Document srcDoc, ArrayList nodes)
{
// Create a blank document.
Document dstDoc = new Document();
// Remove the first paragraph from the empty document.
dstDoc.FirstSection.Body.RemoveAllChildren();
// Import each node from the list into the new document. Keep the original formatting of the node.
NodeImporter importer = new NodeImporter(srcDoc, dstDoc, ImportFormatMode.KeepSourceFormatting);
foreach (Node node in nodes)
{
Node importNode = importer.ImportNode(node, true);
dstDoc.FirstSection.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. Below helper methods used by the ExtractContent method.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
private static void VerifyParameterNodes(Node startNode, Node endNode)
{
// The order in which these checks are done is important.
if (startNode == null)
throw new ArgumentException("Start node cannot be null");
if (endNode == null)
throw new ArgumentException("End node cannot be null");
if (!startNode.Document.Equals(endNode.Document))
throw new ArgumentException("Start node and end node must belong to the same document");
if (startNode.GetAncestor(NodeType.Body) == null || endNode.GetAncestor(NodeType.Body) == null)
throw new ArgumentException("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.
Section startSection = (Section)startNode.GetAncestor(NodeType.Section);
Section endSection = (Section)endNode.GetAncestor(NodeType.Section);
int startIndex = startSection.ParentNode.IndexOf(startSection);
int endIndex = endSection.ParentNode.IndexOf(endSection);
if (startIndex == endIndex)
{
if (startSection.Body.IndexOf(startNode) > endSection.Body.IndexOf(endNode))
throw new ArgumentException("The end node must be after the start node in the body");
}
else if (startIndex > endIndex)
throw new ArgumentException("The section of end node must be after the section start node");
}
private static bool IsInline(Node node)
{
// Test if the node is desendant of a Paragraph or Table node and also is not a paragraph or a table a paragraph inside a comment class which is decesant of a pararaph is possible.
return ((node.GetAncestor(NodeType.Paragraph) != null || node.GetAncestor(NodeType.Table) != null) && !(node.NodeType == NodeType.Paragraph || node.NodeType == NodeType.Table));
}
private static void ProcessMarker(CompositeNode cloneNode, ArrayList nodes, Node node, bool isInclusive, bool isStartMarker, bool isEndMarker)
{
// If we are dealing with a block level node just see if it should be included and add it to the list.
if (!IsInline(node))
{
// Don't add the node twice if the markers are the same node
if (!(isStartMarker && isEndMarker))
{
if (isInclusive)
nodes.Add(cloneNode);
}
return;
}
// 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.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.NextSibling != null && node.NodeType != NodeType.FieldEnd)
node = node.NextSibling;
}
}
// 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 (node.NodeType == NodeType.CommentRangeEnd)
{
while (node.NextSibling != null && node.NodeType != NodeType.Comment)
node = node.NextSibling;
}
// Find the corresponding node in our cloned node by index and return it.
// If the start and end node are the same some child nodes might already have been removed. Subtract the
// Difference to get the right index.
int indexDiff = node.ParentNode.ChildNodes.Count - cloneNode.ChildNodes.Count;
// Child node count identical.
if (indexDiff == 0)
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node)];
else
node = cloneNode.ChildNodes[node.ParentNode.IndexOf(node) - indexDiff];
// Remove the nodes up to/from the marker.
bool isSkip = false;
bool isProcessing = true;
bool isRemoving = isStartMarker;
Node nextNode = cloneNode.FirstChild;
while (isProcessing && nextNode != null)
{
Node currentNode = nextNode;
isSkip = false;
if (currentNode.Equals(node))
{
if (isStartMarker)
{
isProcessing = false;
if (isInclusive)
isRemoving = false;
}
else
{
isRemoving = true;
if (isInclusive)
isSkip = true;
}
}
nextNode = nextNode.NextSibling;
if (isRemoving && !isSkip)
currentNode.Remove();
}
// After processing the composite node may become empty. If it has don't include it.
if (!(isStartMarker && isEndMarker))
{
if (cloneNode.HasChildNodes)
nodes.Add(cloneNode);
}
}

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 7 th and 11 th paragraph. 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. Below example shows how to extract the content between specific paragraphs using the ExtractContent method above. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Gather the nodes. The GetChild method uses 0-based index
Paragraph startPara = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 6, true);
Paragraph endPara = (Paragraph)doc.FirstSection.Body.GetChild(NodeType.Paragraph, 10, true);
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara, endPara, true);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);

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 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. Below example shows how to extract the content between a paragraph and table using the ExtractContent method. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Paragraph startPara = (Paragraph)doc.LastSection.GetChild(NodeType.Paragraph, 2, true);
Table endTable = (Table)doc.LastSection.GetChild(NodeType.Table, 0, true);
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara, endTable, true);
// Lets reverse the array to make inserting the content back into the document easier.
extractedNodes.Reverse();
while (extractedNodes.Count > 0)
{
// Insert the last node from the reversed list
endTable.ParentNode.InsertAfter((Node)extractedNodes[0], endTable);
// Remove this node from the list after insertion.
extractedNodes.RemoveAt(0);
}
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
// Save the generated document to disk.
doc.Save(dataDir);

Extract Content Between Paragraphs Based on Style

You may need to extract the content between paragraphs of the same or different style, 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. Below example shows how to extract content between paragraphs with specific styles using the ExtractContent method. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Gather a list of the paragraphs using the respective heading styles.
ArrayList parasStyleHeading1 = Common.ParagraphsByStyleName(doc, "Heading 1");
ArrayList parasStyleHeading3 = Common.ParagraphsByStyleName(doc, "Heading 3");
// Use the first instance of the paragraphs with those styles.
Node startPara1 = (Node)parasStyleHeading1[0];
Node endPara1 = (Node)parasStyleHeading3[0];
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startPara1, endPara1, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);

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. Below example shows how to extract content between specific runs of the same paragraph using the ExtractContent method. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Retrieve a paragraph from the first section.
Paragraph para = (Paragraph)doc.GetChild(NodeType.Paragraph, 7, true);
// Use some runs for extraction.
Run startRun = para.Runs[1];
Run endRun = para.Runs[4];
// Extract the content between these nodes in the document. Include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startRun, endRun, true);
// Get the node from the list. There should only be one paragraph returned in the list.
Node node = (Node)extractedNodes[0];
// Print the text of this node to the console.
Console.WriteLine(node.ToString(SaveFormat.Text));

Extract Content using a Field

To use a field as marker, the FieldStart node should be passed. The last parameter to the ExtractContent method will define if the entire field is to be included or not. Let’s extract the content between the “FullName” merge field and a paragraph in the document. We use the DocumentBuilder.MoveToMergeField method of DocumentBuilder class. This will return the FieldStart node from the name of merge field passed to it. We will then

In our case let’s set the last parameter passed to the ExtractContent method to false to exclude the field from the extraction. We will render the extracted content to PDF. Below example shows how to extract content between a specific field and paragraph in the document using the ExtractContent method. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
// Use a document builder to retrieve the field start of a merge field.
DocumentBuilder builder = new DocumentBuilder(doc);
// Pass the first boolean parameter to get the DocumentBuilder to move to the FieldStart of the field.
// We could also get FieldStarts of a field using GetChildNode method as in the other examples.
builder.MoveToMergeField("Fullname", false, false);
// The builder cursor should be positioned at the start of the field.
FieldStart startField = (FieldStart)builder.CurrentNode;
Paragraph endPara = (Paragraph)doc.FirstSection.GetChild(NodeType.Paragraph, 5, true);
// Extract the content between these nodes in the document. Don't include these markers in the extraction.
ArrayList extractedNodes = Common.ExtractContent(startField, endPara, false);
// Insert the content into a new separate document and save it to disk.
Document dstDoc = Common.GenerateDocument(doc, extractedNodes);
dataDir = dataDir + RunExamples.GetOutputFilePath(fileName);
dstDoc.Save(dataDir);

Extract Content from a Bookmark

In a document the content that is defined within a bookmark is encapsulated by the BookmarkStart and BookmarkEnd nodes. 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. Below example shows how to extract the content referenced a bookmark using the ExtractContent method. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
string fileName = "TestFile.doc";
Document doc = new Document(dataDir + fileName);
Section section = doc.Sections[0];
section.PageSetup.LeftMargin = 70.85;
// Retrieve the bookmark from the document.
Bookmark bookmark = doc.Range.Bookmarks["Bookmark1"];
// We use the BookmarkStart and BookmarkEnd nodes as markers.
BookmarkStart bookmarkStart = bookmark.BookmarkStart;
BookmarkEnd bookmarkEnd = bookmark.BookmarkEnd;
// Firstly extract the content between these nodes including the bookmark.
ArrayList extractedNodesInclusive = Common.ExtractContent(bookmarkStart, bookmarkEnd, true);
Document dstDoc = Common.GenerateDocument(doc, extractedNodesInclusive);
dstDoc.Save(dataDir + "TestFile.BookmarkInclusive_out.doc");
// Secondly extract the content between these nodes this time without including the bookmark.
ArrayList extractedNodesExclusive = Common.ExtractContent(bookmarkStart, bookmarkEnd, false);
dstDoc = Common.GenerateDocument(doc, extractedNodesExclusive);
dstDoc.Save(dataDir + "TestFile.BookmarkExclusive_out.doc");

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 review 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 template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
Document doc = new Document(dataDir + "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.
CommentRangeStart commentStart = (CommentRangeStart)doc.GetChild(NodeType.CommentRangeStart, 0, true);
CommentRangeEnd commentEnd = (CommentRangeEnd)doc.GetChild(NodeType.CommentRangeEnd, 0, true);
// Firstly extract the content between these nodes including the comment as well.
ArrayList extractedNodesInclusive = Common.ExtractContent(commentStart, commentEnd, true);
Document dstDoc = Common.GenerateDocument(doc, extractedNodesInclusive);
dstDoc.Save(dataDir + "TestFile.CommentInclusive_out.doc");
// Secondly extract the content between these nodes without the comment.
ArrayList extractedNodesExclusive = Common.ExtractContent(commentStart, commentEnd, false);
dstDoc = Common.GenerateDocument(doc, extractedNodesExclusive);
dstDoc.Save(dataDir + "TestFile.CommentExclusive_out.doc");

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 accept 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. You can download template file of this example from here.

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
// The path to the documents directory.
string dataDir = RunExamples.GetDataDir_WorkingWithDocument();
// Open the document we want to convert.
Document doc = new Document(dataDir + "Visitor.ToText.doc");
// Create an object that inherits from the DocumentVisitor class.
MyDocToTxtWriter myConverter = new 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.
Console.WriteLine(myConverter.GetText());
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET
/// <summary>
/// Simple implementation of saving a document in the plain text format. Implemented as a Visitor.
/// </summary>
internal class MyDocToTxtWriter : DocumentVisitor
{
public MyDocToTxtWriter()
{
mIsSkipText = false;
mBuilder = new StringBuilder();
}
/// <summary>
/// Gets the plain text of the document that was accumulated by the visitor.
/// </summary>
public string GetText()
{
return mBuilder.ToString();
}
/// <summary>
/// Called when a Run node is encountered in the document.
/// </summary>
public override VisitorAction VisitRun(Run run)
{
AppendText(run.Text);
// Let the visitor continue visiting other nodes.
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldStart node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldStart(FieldStart fieldStart)
{
// In Microsoft Word, a field code (such as "MERGEFIELD FieldName") follows
// After a field start character. We want to skip field codes and output field
// Result only, therefore we use a flag to suspend the output while inside a field code.
//
// Note this is a very simplistic implementation and will not work very well
// If you have nested fields in a document.
mIsSkipText = true;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldSeparator node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldSeparator(FieldSeparator fieldSeparator)
{
// Once reached a field separator node, we enable the output because we are
// Now entering the field result nodes.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when a FieldEnd node is encountered in the document.
/// </summary>
public override VisitorAction VisitFieldEnd(FieldEnd fieldEnd)
{
// Make sure we enable the output when reached a field end because some fields
// Do not have field separator and do not have field result.
mIsSkipText = false;
return VisitorAction.Continue;
}
/// <summary>
/// Called when visiting of a Paragraph node is ended in the document.
/// </summary>
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
// When outputting to plain text we output Cr+Lf characters.
AppendText(ControlChar.CrLf);
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyStart(Body body)
{
// We can detect beginning and end of all composite nodes such as Section, Body,
// Table, Paragraph etc and provide custom handling for them.
mBuilder.Append("*** Body Started ***\r\n");
return VisitorAction.Continue;
}
public override VisitorAction VisitBodyEnd(Body body)
{
mBuilder.Append("*** Body Ended ***\r\n");
return VisitorAction.Continue;
}
/// <summary>
/// Called when a HeaderFooter node is encountered in the document.
/// </summary>
public override VisitorAction VisitHeaderFooterStart(HeaderFooter headerFooter)
{
// Returning this value from a visitor method causes visiting of this
// Node to stop and move on to visiting the next sibling node.
// The net effect in this example is that the text of headers and footers
// Is not included in the resulting output.
return VisitorAction.SkipThisNode;
}
/// <summary>
/// Adds text to the current output. Honours the enabled/disabled output flag.
/// </summary>
private void AppendText(string text)
{
if (!mIsSkipText)
mBuilder.Append(text);
}
private readonly StringBuilder mBuilder;
private bool mIsSkipText;
}

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 contains control characters that designate special elements such as field, end of 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. 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-.NET
Document doc = new Document();
// Enter a dummy field into the document.
DocumentBuilder builder = new DocumentBuilder(doc);
builder.InsertField("MERGEFIELD Field");
// GetText will retrieve all field codes and special characters
Console.WriteLine("GetText() Result: " + doc.GetText());
// 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.
Console.WriteLine("ToString() Result: " + doc.ToString(SaveFormat.Text));