Search code examples
sharepointweb-partscaml

CAML to search for pages returns all files and folders in a site


I am trying to write a simple web part for Sharepoint 2013 that searches for all pages of a certain content type and outputs a list of their titles. I am using a CAML query to search for that. But no matter what query, the result I have is just a list of all files and folders in this Sharepoint site.

Finally, I reduced the CAML query to a simple "find everything that starts with the letter T", but still the result is outputting all files and folders in the root level of the site.

What am I doing wrong?

    protected override void CreateChildControls()
    {
        Label label1 = new Label();

        try
        {
            SPQuery query = new SPQuery();
            query.Query = @"<Query>
                            <Where>
                              <BeginsWith>
                                <FieldRef Name='Title'></FieldRef>
                                <Value Type='Text'>T</Value>
                              </BeginsWith>
                            </Where>
                            </Query>";

            using (SPSite site = new SPSite("https://xxxxxx/sites/xxxxx/en/xxxx/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    PublishingWeb pubweb = PublishingWeb.GetPublishingWeb(web);
                    PublishingPageCollection collection = pubweb.GetPublishingPages(query);

                    //now output the results of the query                        
                    label1.Text = "Items: " + collection.Count.ToString();
                    for (int i = 0; i < collection.Count; i++)
                    {
                        label1.Text += collection[i].Title + "<br>";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            label1.Text = ex.Message;
        }


        Controls.Add(label1);
    }

Solution

  • Weirdly, you need to do two things:

    1) Remove the opening and closing tag;

    2) Make sure the query does not start or end with a blank line.

    Then the results will change the the correct ones.