Wednesday, July 14, 2010

Accessing SharePoint List Data as XML

REF: http://vspug.com/dwise/2008/01/10/accessing-sharepoint-list-data-as-xml


The other day, I found myself in need of a way to access SharePoint list data as XML but the only method available to me was a simple http GET. This is not too bad, but what can I get from SharePoint via GET? RSS is too limited and scraping the page is too painful and error-prone to even contemplate.

It turns out that there is an option available in 2007 that was carried forward from SharePoint 2003 / FrontPage days: owssvr.dll. But this isn't some forgotten FrontPage artifact, it is still a central part of SharePoint. In fact, if you pull up a list view and then view the source looking for owssvr.dll, you will see that this is the mechanism behind both the Export to Spreadsheet and Open with Access options on the list Actions menu.

How It Works
Simply put together a URL like this:

http://MyServer/[site]/_vti_bin/owssvr.dll?Cmd=Display&List={listGuid}&XMLDATA=TRUE

This will only return the fields that are defined on the default view of the list. If you need specific fields then you need to create a view with those fields and pass the View ID as well, like this:

http://…/owssvr.dll?Cmd=Display&List={listGuid}&view={viewGuid}&XMLDATA=TRUE

Specifying Fields to be Returned
There is also a Query parameter that lets you specify which fields are to be included in the resulting XML, regardless of how the view is defined. For example, if you wanted just to bring back the Title and Status Fields, you would add the field names separated by spaces (URL Encoded, of course) like "&Query=Title%20Status". If you want to return all fields, use an asterisk (*) instead of field names.

http://…/owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE

Filtering Data
Regardless of whether you pass a view or use the default it will still use the filter defined by that view. Not bad, but you can trim this data even more by including a filter of your own using the FilterFieldn and FilterValuen arguments in the querystring. These are the same values that are passed when you use the filter options in the column headers of a view which makes it pretty easy to track down exactly what needs to be passed. Simply pull up the view that is your starting point and use the column filters to create your desired filter. Once you have it, grab all of the FilterField and FilterValue items from the querystring and add them on to yours.

http://…/owssvr.dll?Cmd=Display&List={listGuid}&query=Title%20Status&XMLDATA=TRUE&FilterField1=Status&FilterValue1=In%20Progress

For a full list of what can be done with this technique, check out the URL Protocol or the older Using the URL Protocol on MSDN.

No comments:

Post a Comment