The FOR XML and FOR JSON clauses are invalid in views, inline functions, derived tables, and subqueries when they contain ...

The FOR XML and FOR JSON clauses are invalid in views, inline functions, derived tables, and subqueries when they contain a set operator. To work around, wrap the SELECT containing a set operator using derived table or common table expression or view and apply FOR XML or FOR JSON on top of it.