Question

I want to retrieve a specific item from a list named "Pages" in a specific sharepoint site. I want the query to only return the specific item associated with the FileLeafRef that I'm querying. I've constructed a CAML query that I've tested out suing the SP CAML Query helper tool, so I think the CAML query is good; I just can't figure out how to query for the item using the client context. Here's my existing code:

    Dim FileLeafRef As String = "SomeArbitrarilyNamedThing.aspx"

    Dim clientContext As New Microsoft.SharePoint.Client.ClientContext("http://myfqdn/newsandmedia/companynews")
    Dim theList As Microsoft.SharePoint.Client.List = clientContext.Web.Lists.GetByTitle("Pages")

    Dim camlQuery As New Microsoft.SharePoint.Client.CamlQuery()

    camlQuery.ViewXml = String.Format("<Query><Where><Eq><FieldRef Name=""FileLeafRef"" /><Value Type=""Text"">{0}</Value></Eq></Where></Query>", FileLeafRef)
    Console.WriteLine(camlQuery.ViewXml)


    Dim listItems As Microsoft.SharePoint.Client.ListItemCollection = theList.GetItems(camlQuery)

    clientContext.Load(theList)
    clientContext.Load(listItems)
    clientContext.ExecuteQuery()

After the call to ExecuteQuery, when I take a look at the listItems collection, it has more than the one item that I'm querying for. (specifically it has 15, but there should only be one item with the requested FileLeafRef). Can anyone please help me out by identifying what's wrong with this code?

Thanks

EDIT: I've since discovered that if I wrap the camlQuery xml with View tags, it returns the list item that I wanted. I don't know why. Can anyone explain what those tags do in this context, and why the query returned 15 results initially instead of just 1?

Was it helpful?

Solution

It happens because client context CamlQuery object accepts not only query but the whole view. That is why you need to provide View xml. You can find view element structure here.

Probably it returned 15 items initially because you view xml was incorrect. I guess it returned all items in the list. I've seen this behavior before when working with server object model - if your caml query has incorrect structure or any mistakes then all list items are returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top