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.
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 –
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.
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.