Paging in FetchXml

By | December 22, 2017

Was working on the code that needed paging with FetchXml.. There is a good example on MSDN:

But, in case you don’t want to mess with XmlDocument (not that it’s really that messy), you can easily do the same using simple string Replace – there is an example below. The only tricky part is that a few characters in the paging cookie have to be decoded before you can put it into the FetchXml, but that’s about it:

        public EntityCollection RetrieveContacts(IOrganizationService service, int page, string pagingCookie)
            if (pagingCookie != null && pagingCookie != "")
                pagingCookie = pagingCookie.Replace("\"", "'").Replace(">", "&gt;").Replace("<", "&lt;");
            string fetchXml =
                    @"<fetch version=""1.0""
                        <entity name=""contact"">
                          <attribute name=""contactid"" />
            fetchXml = string.Format(fetchXml, page, pagingCookie);
            var qe = new FetchExpression(fetchXml);
            var result = service.RetrieveMultiple(qe);
            return result;

                int pageNumber = 1;
                 string pagingCookie = “”;
                 EntityCollection result = null;
                     result = RetrieveContacts(service, pageNumber, pagingCookie);
                     foreach (var e in result.Entities)
                     pagingCookie = result.PagingCookie;
                 } while (result.MoreRecords);

One thought on “Paging in FetchXml

  1. James

    I am facing a similar issue but I get “required white space missing” every time.

    i have tried a lot but not able to handle the exception.

    I have even changed the retrieved paging cookie format before passing it to string fetchxml.
    (*using single quotes in attribute values.)
    if (pagingCookie != null && pagingCookie != “”)
    pagingCookie = pagingCookie.Replace(“\””, “‘”).Replace(“>”, “>”).Replace(“<", "<");

    let me know what i should do.


Leave a Reply

Your email address will not be published. Required fields are marked *