Dynamics 365 – FetchXML Throwing ‘Invalid XML.’ due to Special Characters

Today’s just a very short article that will hopefully serve as a reminder to myself and a help to others searching for how to resolve the ‘Invalid XML’ error that is generated by C# plugins and the likes utilising FetchXML for querying CRM data.

FetchXML1

Main Cause

The main cause is simply that you’ve incorrectly formatted your FetchXML query, a properly formatted FetchXML will look something like one of the below examples –

C#

FetchXML2

Raw FetchXML

FetchXML3

If you’re not confident in using FetchXML then a brilliant way to get close to what you want is to set up an Advanced Find query in CRM, making sure that it returns the records you’re expecting then click the ‘Download FetchXML’ button in the toolbar which will give you a copy of the FetchXML used to retrieve the records. You will have to reformat it slightly for it to be usable in C# but it’s certainly easier than writing it by hand.

Other Cause (Special Characters)

But what if you know it’s all properly formatted but it’s still throwing an error?

Well, then you’re likely coming across an issue with special characters, which will most often catch you out when filtering by fields such as an Email Subject which can often contain ampersands and other nasty characters which will ruin your FetchXML.

Luckily there’s a very simple solution.

WebUtility

In your project wrap the value that’s causing the error with ‘WebUtility.HtmlEncode’  which will encode the values so that it no longer causes issues. Below is an example where I’ve modified the first FetchXML screenshot above to use the HtmlEncode method to avoid these issues.

FetchXML4

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.