Tuesday, July 20, 2010

Convert XML to a CAML Query with Powershell

You might ask yourself, “Why would I want to do that?”  Well, as you probably could tell, I use SharePoint A LOT!  I’ve recently started deep diving into DVWP’s (Data View Web Parts), thanks to the USPJA and Marc Anderson’s excellent DVWP course.  CAML piqued my interest a whole lot and because of that I found easy ways to construct my CAML queries.  These free tools are absolutely excellent: U2U CAML Query Builder and Stramit SharePoint CAML Viewer.  These tools are simply the best when it comes to ease of use and quality of results.  However, with a DVWP, I cannot simply copy and paste the query from these tools into it.  I must escape all of the characters CAML chokes on.  For that I’ve built a simple tool in Powershell that will ask you which file you’d like to convert and then it’ll even trim the white space in the file.  Literally all you have to do is copy the query from one of these tools to notepad and save it.  Run my XML2CAML script and your CAML Query is ready to be dropped into your DVWP.  I know there are other tools out there that are similar, but are they free?  Also do they trim the whitespace for you? 

I hope you find this as useful as I do…