Free Support Forum - aspose.com

Deleting the remainder of a document

What's a good way to delete the remaining contents of a document after a particular node? For example, if I have located a particular paragraph node I'm searching for, how can I then remove all contents following that node?

Similarly, what's a good way to remove all contents between two particular nodes?

As simple as this task may seem there is no trivial solution to it. That is due to a treelike character of the document model. It seems that the most robust and universal approach is to insert section breaks at the beginning and end of the removed area and remove the sections in this area afterwards.

This approach works fine as far as I have tested it, although I cannot guarantee it covers all possible scenarios.

Here is the code:

///

/// Removes the document content beginning with the specified node.

///

/// Node to begin removal with.

private void RemoveDocumentRemainder(Node node)

{

Document doc = node.Document;

DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveTo(node);

Section nodeSection = builder.CurrentSection;

builder.InsertBreak(BreakType.SectionBreakContinuous);

while (nodeSection != doc.LastSection)

doc.LastSection.Remove();

}

///

/// Removes the document content inclusively between the specified nodes.

///

/// The first node to remove.

/// The last node to remove.

private void RemoveDocumentPart(Node nodeStart, Node nodeEnd)

{

Document doc = nodeStart.Document;

DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveTo(nodeStart);

builder.InsertBreak(BreakType.SectionBreakContinuous);

int indexSectionStart = doc.IndexOf(builder.CurrentSection);

builder.MoveTo(nodeEnd);

builder.InsertBreak(BreakType.SectionBreakContinuous);

Section sectionEnd = builder.CurrentSection;

while(doc.Sections[indexSectionStart] != sectionEnd || doc.Sections[indexSectionStart] != doc.LastSection)

{

doc.Sections[indexSectionStart].Remove();

}

sectionEnd.Remove();

((Section)doc.Sections[indexSectionStart - 1]).AppendContent(sectionEnd);

}

Try it and please report if you have any difficulties using it.