How to query an Xslt Listviewwebpart using CAML query?

Consider, you have an Xslt Listviewwebpart added to a page, and data in the webpart should be filtered based on logged in user’s details. Assume the CAML query includes multiple AND and OR conditions. For simple AND conditions, we can apply filter from the browser. But, how are we going to handle the complex queries? Updating a view based on logged in user’s credentials and, applying the view to the listviewwebpart won’t work out. If we go ahead with view and, multiple users access the page simultaneously then view of one user will be displayed for another user, which is incorrect.

The below steps are going to handle the complex queries-

1)  Retrieve the filter values specific to the logged in user.

2)  Create an XSLT Listviewwebpart object at run time.

3)  Assign the list ID, default View ID, web ID to the XSLT Listviewwebpart object. Get the default view xml and set it as xml definition for the XSLT Listviewwebpart object.

XsltListViewWebPart oListViewWP = new XsltListViewWebPart();

oListViewWP.ListName = list.ID.ToString("B").ToUpper();

oListViewWP.ViewGuid = webPartView.ID.ToString("B").ToUpper();

oListViewWP.WebId = web.ID;

oListViewWP.XmlDefinition = webPartView.GetViewXml();

In the above code snippet,; list refers to the source SPList; webPartView refers to the default view of the source list; web refers to the source web object.

4)  Our next step will be set the xml definition of the XSLT Listviewebpart object based on our CAML query.

XmlDocument xml = new XmlDocument();

xml.LoadXml(oListViewWP.XmlDefinition);

XmlElement viewXml = xml["View"];

XmlNode viewQuery = viewXml.SelectSingleNode("//Query");

XmlNode where = viewQuery.SelectSingleNode("//Where");

if (where == null)

{

where = xml.CreateElement("Where");

viewQuery.AppendChild(where);

}

if (where.ChildNodes.Count == 1)

{

where.InnerXml = where.InnerXml.Replace(where.FirstChild.OuterXml, _StrQuery);

}

else

{

where.InnerXml = _StrQuery;

}

oListViewWP.XmlDefinition = xml.InnerXml;

Controls.Add(oListViewWP);

In the above code snippet, _StrQuery refers to the CAML query, and we are replacing the where node of the XSLT Listviewwebpart xmlDefinition with the CAML query.

And now we are done with querying an XSLT Listviewwebpart based on a CAML query. The only catch here is if we modify the xmlDefintion of an already added XSLT Listviewwebpart, the data won’t be filtered based on the modified xmlDefintion. Thus, we will have to proceed with creation of XSLT Listviewwebpart at run time.