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

Free Support Forum - aspose.com

Check merge field problem

I am using the follow function to check if a merge field exists, it’s working for long. However, recently I got an exception for a document, that document contain many chinese character, I don’t know whether it’s the root cause.
I traced in debug mode and found that, the variable got the value " MERGEF", it seems could not get the full node text, the expected string should be " MERGEFIELD field1 \* MERGEFORMAT ".
This occurs randomly, not in every merge field and I could not expect when it would occur.

private bool FieldExists(string name)
{
    string s;
    string[] s1;
    string fieldname;
    NodeList fieldStarts = doc.SelectNodes("//FieldStart");
    foreach (FieldStart fieldStart in fieldStarts)
    {
        if (fieldStart.FieldType == FieldType.FieldMergeField)
        {
            s = fieldStart.NextSibling.GetText();
            s1 = s.Split(new char[] { ' ' });
            fieldname = s1[3];
            if (fieldname == name)
                return true;
        }
    }
    return false;
}

Hi
Thanks for your request. This occurs because field code can be represented by sequence of Run nodes. Please try using the following code:

private bool FieldExists(string name, Document doc)
{
    // Regex that will be used to extract name of mergefield
    Regex regex = new Regex(@"\s*(?\S+)\s+(?\S+)\s+(?.+)");
    // Get FieldSatart nodes from the docuemnt
    NodeCollection fieldStarts = doc.GetChildNodes(NodeType.FieldStart, true);
    foreach (FieldStart fieldStart in fieldStarts)
    {
        if (fieldStart.FieldType == FieldType.FieldMergeField)
        {
            Node node = fieldStart;
            // Get field code
            string fieldCode = string.Empty;
            while (node.NodeType != NodeType.FieldEnd)
            {
                if (node.NodeType == NodeType.Run)
                {
                    fieldCode += ((Run)node).GetText();
                }
                node = node.NextSibling;
            }
            // Get field name
            Match match = regex.Match(fieldCode);
            string fieldName = match.Groups["name"].Value;
            if (fieldName == name)
                return true;
        }
    }
    return false;
}

Hope this helps.
Best regards.