Fill MergeField Using OpenXMl
<p>I am trying to replace mergefields in word file with my data using OpenXML.</p>

<p>I think there is no problem in the code as sometimes it works fine in some templates and sometimes the mergefields isn't replaced.</p>

<p>Is there a problem in inserting Mergefields inside word template ? I don't know what is the problem.</p>

<p>Below is the code I use :</p>

<pre><code> public void Fill_Document_Fields(Dictionary&lt;string, string&gt; Fields, string FilePath)
    {
        try
        {
            using (WordprocessingDocument Doc = WordprocessingDocument.Open(FilePath, true))
            {
                foreach (FieldCode field in Doc.MainDocumentPart.RootElement.Descendants&lt;FieldCode&gt;())
                {
                    string FieldName =string.Empty;
                    try
                    {
                        FieldName = field.Text.Trim().Split(' ')[2];
                    }
                    catch
                    {
                        FieldName = field.Text.Trim();
                    }


                    foreach (Run run in Doc.MainDocumentPart.Document.Descendants&lt;Run&gt;())
                    {
                        foreach (Text txtFromRun in run.Descendants&lt;Text&gt;().Where(a =&gt; a.Text == "«" + FieldName + "»"))
                        {
                            string itemValue;
                            if (Fields.TryGetValue(txtFromRun.Text, out itemValue))
                            {
                                txtFromRun.Text = itemValue;
                            }
                        }
                    }

                }
            }
        }
        catch 
        {
        }
    }
</code></pre>