Free Support Forum - aspose.com

Replacing keywords surrounded by �{}� in a .doc document

<!–[if gte mso 10]> /* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Calibri","sans-serif"; mso-bidi-font-family:"Times New Roman";}

<![endif]–><!–[if gte mso 9]>
<w:WordDocument>
<w:View>Normal</w:View>
<w:Zoom>0</w:Zoom>
<w:TrackMoves/>
<w:TrackFormatting/>
<w:PunctuationKerning/>
<w:ValidateAgainstSchemas/>
<w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid>
<w:IgnoreMixedContent>false</w:IgnoreMixedContent>
<w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText>
<w:DoNotPromoteQF/>
<w:LidThemeOther>EN-CA</w:LidThemeOther>
<w:LidThemeAsian>ZH-CN</w:LidThemeAsian>
<w:LidThemeComplexScript>X-NONE</w:LidThemeComplexScript>
<w:Compatibility>
<w:BreakWrappedTables/>
<w:SnapToGridInCell/>
<w:WrapTextWithPunct/>
<w:UseAsianBreakRules/>
<w:DontGrowAutofit/>
<w:SplitPgBreakAndParaMark/>
<w:EnableOpenTypeKerning/>
<w:DontFlipMirrorIndents/>
<w:OverrideTableStyleHps/>
<w:UseFELayout/>
</w:Compatibility>
<m:mathPr>
<m:mathFont m:val=“Cambria Math”/>
<m:brkBin m:val=“before”/>
<m:brkBinSub m:val="–"/>
<m:smallFrac m:val=“off”/>
<m:dispDef/>
<m:lMargin m:val=“0”/>
<m:rMargin m:val=“0”/>
<m:defJc m:val=“centerGroup”/>
<m:wrapIndent m:val=“1440”/>
<m:intLim m:val=“subSup”/>
<m:naryLim m:val=“undOvr”/>
</m:mathPr></w:WordDocument>
<![endif]–><!–[if gte mso 10]>

/* Style Definitions */ table.MsoNormalTable {mso-style-name:"Table Normal"; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Calibri","sans-serif"; mso-bidi-font-family:"Times New Roman";}

<![endif]–>

In our application, we need to replace keywords surrounded by “{}” with the real value stored in the database. E.g. Replacing “{Title}” with “Mrs”, e.t.c

I tried to use the following code and it didn’t work. It always returns a number ‘0’.
int number = doc.Range.Replace("{Title}", "My title", true, true);

If I replace "{Title}" to "Title", it is able to find all the "Title"s and replace them with "My title". So it is the "{ }" that causes the problem.

Is there a way to workaround this?


Thanks!

I have fixed the problem by using regular expression:

int number = doc.Range.Replace( new Regex("\{Title\}", RegexOptions.IgnoreCase), “My title”);

Are there any other solutions to this problem?

Thanks!


Hi

Thanks for your request. Your solution is correct. Also, since there can be a lot of placeholders enclosed into curly brackets in your template, I would suggest you to use IReplacingCallback. In this case using one Replace method, you can replace all placeholders. Please see the following code:

[Test]

public void Test001()

{

Document doc = new Document(@"Test001\in.doc");

// Lets suppose the text placeholders in your document are represented by variable name enclosed in curly brakets.

doc.Range.Replace(new Regex(@"\{(?.*?)\}"), new PlaceholderReplacer(), false);

doc.Save(@"Test001\out.doc");

}

private class PlaceholderReplacer : IReplacingCallback

{

///

/// This method is called by the Aspose.Words find and replace engine for each match.

///

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// Get variable name

string varName = e.Match.Groups["varName"].Value;

// Get value that shouls be inserted at place of variable.

// In your case you will probably get value from database or other datasource.

// To demonstrate the technique I just format valye from variable name.

string varValue = string.Format("This is value of {0}", varName);

// Specify value that should be a replacement.

e.Replacement = varValue;

// Signal replacing engine to replace the value.

return ReplaceAction.Replace;

}

}

Hope this could be useful for you.

Best regards,

Hi,

Thank you for your solution. I have incorporated it into my project and it works fine. Except that there is a requirement that if a PlaceHolder is in the document’s header or footer, it shouldn’t be replaced.

Is there a way to do such checking?

Thanks!


Never mind. I have figured it out.

Regex regex = new Regex(@"{(?.*?)}");

foreach (Section section in doc.Sections)
{
//Process only body
section.Body.Range.Replace(regex, new PlaceholderReplacer(mergeValues), false);
}

Thanks anyway!

Hi

It is perfect that you managed to resolve the issue. You can achieve the same using another approach. You can simply check whether the match note is inside header/footer and if so just skip replacing:

private class PlaceholderReplacer : IReplacingCallback

{

///

/// This method is called by the Aspose.Words find and replace engine for each match.

///

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// If the match ode is inside header or footer skip replacing.

if (e.MatchNode.GetAncestor(NodeType.HeaderFooter) != null)

return ReplaceAction.Skip;

// Get variable name

string varName = e.Match.Groups["varName"].Value;

// Get value that shouls be inserted at place of variable.

// In your case you will probably get value from database or other datasource.

// To demonstrate the technique I just format valye from variable name.

string varValue = string.Format("This is value of {0}", varName);

// Specify value that should be a replacement.

e.Replacement = varValue;

// Signal replacing engine to replace the value.

return ReplaceAction.Replace;

}

}

Best regards,