Hello, is there a way to do a replace operation on all nodes of a document starting from the current node (since myDocument.Range.Replace will search from the beginning of the document and i don’t want to replace nodes that are located before the current node) ?
Sincerely.
@aaronArchest I am afraid there is no way to search from the specified position/node using Aspose.Words. You can consider implementing the following approach - loop the nodes starting from the specified position and do Node.Range.Replace
on each node. For example you can achieve this using DocumentVisitor
:
Document doc = new Document(@"C:\Temp\in.docx");
// Do replacemnt after the second paragraph.
DocumentVisitorReplaceAfterParagraph replacer = new DocumentVisitorReplaceAfterParagraph(doc.FirstSection.Body.Paragraphs[1], "test", "replacement");
doc.Accept(replacer);
doc.Save(@"C:\Temp\out.docx");
private class DocumentVisitorReplaceAfterParagraph : DocumentVisitor
{
public DocumentVisitorReplaceAfterParagraph(Paragraph startFrom, string pattern, string replacement)
{
mStartFrom = startFrom;
mPattern = pattern;
mReplacement = replacement;
}
public override VisitorAction VisitParagraphStart(Paragraph paragraph)
{
if (mDoReplace)
paragraph.Range.Replace(mPattern, mReplacement);
return VisitorAction.Continue;
}
public override VisitorAction VisitParagraphEnd(Paragraph paragraph)
{
if(paragraph == mStartFrom)
mDoReplace = true;
return VisitorAction.Continue;
}
private bool mDoReplace = false;
private Paragraph mStartFrom;
private string mPattern;
private string mReplacement;
}