We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Replace string with another document

Hey,

I have a word document that is going to be translaed for several languages.
The document consists of MergeField and regular strings. All the strings are going to be translated.
Our translation guys are working with XML files (Resx).
We wrote a C# program that replaces the place holders with the relevant strings that are taken from the XML.
In some cases the block of text that should be inserted should contain also MergeFields.

What I’m doing in order to insert the MergeFields into the block of text is as following:

//Replace the key (place holder) with the Value (block of text).
doc.Range.Replace(key, value, false, true);

Document mergeFieldDoc = new Document();
DocumentBuilder builder = new DocumentBuilder(mergeFieldDoc);
string fieldName = "MyMergeField";
builder.InsertField(string.Format(@"MERGEFIELD {0} \* MERGEFORMAT", fieldName), string.Format(@"«MergeField:{0}»", fieldName));

//calling the following method that was found in the Aspose.Help.CHM file
//All the other method from the CHM were copied also....
//What I want to do here is to replace the fieldKey from the 'doc' document with the content of the created mergeFieldDoc
ReplaceTextWithDoc(doc, mergeFieldDoc, fieldKey);

That is my problem:

the ReplaceTextWithDoc method calls InsertDocEvaluator which should do the replacement
but it replaces all the block that contains the text to be replaced and not only the fieldKey string.

private ReplaceAction InsertDocEvaluator(object sender, ReplaceEvaluatorArgs e)
{
    Paragraph para = (Paragraph)e.MatchNode.ParentNode;
    // Insert document after the paragraph, containing match text.
    InsertDocument(para, insertDoc);
    // Remove the paragraph with the match text.
    //para.Remove();
    return (ReplaceAction.Replace);
}

Regards


Dan Oren

AppScan Development team

IBM R&D labs, Israel

Office: +972-9-9586077 ext.238

Cell: +972-52-3416300

DanOren@il.ibm.com


Hi

Thanks for your inquiry. I think that you should do the following changes in your code.

private void ReplaceTextWithDoc(Document mainDoc, Document insertedDoc, string text)
{
    // Assign the reference to the inserted document to the private member of the container class
    // to let InsertDocEvaluator could get a hold of it.
    this.insertDoc = insertedDoc;
    mainDoc.JoinRunsWithSameFormatting();
    mainDoc.Range.Replace(new Regex("placeholder"), new ReplaceEvaluator(InsertDocEvaluator), false);
}

private ReplaceAction InsertDocEvaluator(object sender, ReplaceEvaluatorArgs e)
{
    Document insertDoc = new Document(@"Test277\src.doc");
    //Get MatchNode
    Run run1 = (Run)e.MatchNode;
    //Create Run
    Run run2 = (Run)run1.Clone(true);
    //Get index of match value
    int index = run1.Text.IndexOf(e.Match.Value);
    //Split text in match node
    run2.Text = run1.Text.Substring(0, index);
    run1.Text = run1.Text.Substring(index + e.Match.Value.Length);

    run1.ParentParagraph.InsertBefore(run2, run1);
    DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);
    //Move to run1
    builder.MoveTo(run1);
    //Insert Paragraph break
    builder.InsertBreak(BreakType.ParagraphBreak);

    Paragraph para = (Paragraph)builder.CurrentParagraph.PreviousSibling;
    // Insert document after the paragraph, containing match text.
    InsertDocument(para, insertDoc);
    // Remove the paragraph with the match text.
    //para.Remove();
    return (ReplaceAction.Skip);
}

The problem occurs because you replace whole paragraph instead one word.

Hope this helps.

Best regards.

Hey,

Thanks for the quick response.

I didn’t understand what is “JoinRunsWithSameFormatting”.

also, instead of getting:

This report holds the results of a web application security scan performed on the [Assignment Name] application by the [Company Name] security team.

The scan revealed «AS:ScanDataIssuesHigh» high severity security issues, �AS:ScanDataIssuesMedium� medium severity issues and �AS:ScanDataIssuesLow� low severity issues in this application. The findings have been consolidated for this Executive Summary and Detailed Summary. Additional information is contained within the Detailed Vulnerability Information section of this report.

I’m getting:

This report holds the results of a web application security scan performed on the [Assignment Name] application by the [Company Name] security team.
The scan revealed
«AS:ScanDataIssuesHigh»
high severity security issues, �AS:ScanDataIssuesMedium� medium severity issues and �AS:ScanDataIssuesLow� low severity issues in this application. The findings have been consolidated for this Executive Summary and Detailed Summary. Additional information is contained within the Detailed Vulnerability Information section of this report.

There seems to be a problem with the new line somehow…

Could you please help me with this ?

10’X

Dan

Hi

Thanks for your inquiry. Please try using the following InsertDocument method instead yours.

public void InsertDocument(Node insertAfterNode, Document srcDoc)
{
    Document dstDoc = insertAfterNode.Document;
    //Content of first paragraph of srcDoc will be apended to this parafraph
    Paragraph insertAfterParagraph = insertAfterNode as Paragraph;
    //Content of last paragraph of srcDoc will be apended to this parafraph
    Paragraph insertBeforeParagraph = insertAfterNode.NextSibling as Paragraph;
    //We will be inserting into the parent of the destination paragraph.
    CompositeNode dstStory = insertAfterNode.ParentNode;
    //Remove empty paragraphs from the end of document
    while (!srcDoc.LastSection.Body.LastParagraph.HasChildNodes)
    {
        srcDoc.LastSection.Body.LastParagraph.Remove();
    }

    //Loop through all sections in the source document.
    foreach (Section srcSection in srcDoc.Sections)
    {
        //Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            //Do not insert node if it is a last empty paragarph in the section.
            Paragraph para = srcNode as Paragraph;
            if ((para != null) && para.IsEndOfSection && (!para.HasChildNodes))
            {
                break;
            }

            //If current paragraph is first paragraph of srcDoc
            //then appent its content to insertAfterParagraph
            if (srcNode.Equals(srcDoc.FirstSection.Body.FirstParagraph))
            {
                foreach (Node node in para.ChildNodes)
                {
                    Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                    insertAfterParagraph.AppendChild(dstNode);
                }

                //If subdocument contains only one paragraph
                //then copy content of insertBeforeParagraph to insertAfterParagraph
                //and remove insertBeforeParagraph
                if (srcDoc.FirstSection.Body.FirstParagraph.Equals(srcDoc.LastSection.Body.LastParagraph))
                {
                    while (insertBeforeParagraph.HasChildNodes)
                    {
                        insertAfterParagraph.AppendChild(insertBeforeParagraph.FirstChild);
                    }
                    insertBeforeParagraph.Remove();
                }
            }
            //If current paragraph is last paragraph of srcDoc
            //then appent its content to insertBeforeParagraph
            if (srcNode.Equals(srcDoc.LastSection.Body.LastParagraph))
            {
                Node previouseNode = null;
                foreach (Node node in para.ChildNodes)
                {
                    Node dstNode = dstDoc.ImportNode(node, true, ImportFormatMode.KeepSourceFormatting);
                    if (previouseNode == null)
                    {
                        insertBeforeParagraph.InsertBefore(dstNode, insertBeforeParagraph.FirstChild);
                    }
                    else
                    {
                        insertBeforeParagraph.InsertAfter(dstNode, previouseNode);
                    }
                    previouseNode = dstNode;
                }
            }
            else
            {
                //This creates a clone of the node, suitable for insertion into the destination document.
                Node newNode = dstDoc.ImportNode(srcNode, true, ImportFormatMode.KeepSourceFormatting);
                //Insert new node after the reference node.
                dstStory.InsertAfter(newNode, insertAfterNode);
                insertAfterNode = newNode;
            }
        }
    }
}

Also please check the following link. I think it should be useful for you.

Best regards.