Skip to main content
 首页 » 编程设计

c#之CAML "In"SharePoint Services 3 (SharePoint 2007) 的等效运算符

2024年02月20日12www_RR

今天我发现需要编写一个使用 WHERE [Field] IN [Values] 的 CAML 查询。我想查询一个列表,其中列表项的标题包含在一个字符串集合中。在运行我的查询时收到几个错误后,我意识到 In 运算符是 SharePoint 2010 的新功能,但我仍在 SharePoint 2007 中。因此,唯一的选择是使用多个 Or 运算符。此外,Or 运算符一次只能对 2 个值进行运算,因此这需要嵌套的 Or 运算符。如何构建这样的查询?请参阅下面我的解决方案。

请您参考如下方法:

在找到这个解决方案之前,我偶然发现了几种方法。我不确定它的可扩展性,但它适合我的需要,所以我想我会分享它。这个递归方法应该返回等同于

WHERE Title IN ([Title1], [Title2],...[TitleN])  

对于 1-N 字符串标题的列表。

private string _camlTitleEq = "<Eq>" + 
                                 "<FieldRef Name=\"Title\" />" + 
                                 "<Value Type=\"Text\">{0}</Value>" + 
                              "</Eq>"; 
 
private XElement BuildOrClause(List<string> listItemTitles, int index) 
{ 
    //If we've reached the last item in the list, return only an Eq clause 
    if (index == listItemTitles.Count - 1) 
        return XElement.Parse(String.Format(_camlTitleEq, listItemTitles[index])); 
    else 
    { 
        //If there are more items in the list, create a new nested Or, where 
        //the first value is an Eq clause and the second is the result of BuildOrClause 
        XElement orClause = new XElement("Or"); 
        orClause.Add(XElement.Parse(String.Format(_camlTitleEq, listItemTitles[index]))); 
        orClause.Add(BuildOrClause(listItemTitles, index + 1)); 
        return orClause; 
    } 
} 

你可以像这样使用它:

SPQuery query = new SPQuery(); 
string titleIn = BuildOrClause(listItemTitles, 0).ToString(SaveOptions.DisableFormatting); 
 
query.Query = "<Where>" + 
                  titleIn + 
              "</Where>"; 

我希望这对仍在使用 SP 2007 的人有所帮助。欢迎提供建设性的反馈!如果您使用的是 SharePoint 2010,请使用已内置的 In Operator .