Query Child Content Types in your CAML Query
The Content Query Web Part that ships with MOSS and is enabled with the Publishing Feature has an option to include the child content types of that content type in filtering the data. I wanted to replicate this functionality in my own WebPart that utilized the SPSiteDataQuery to query the site. The SPSiteDataQuery accepts a CAML query to filter the results.
It is easy enough to query for all documents in a site that are of content type x:
<Where>
<Eq>
<FieldRef Name=’ContentType’/>
<Value Type=’Text’>HR Document</Value>
</Eq>
</Where>
But what happens if you want to query all children of content type x. In this example if you had CV, Application Form e.t.c. which all inherited from HR Document how do you build your query. You can add each additional Content Type into the WHERE clause of the CAML query, but this is an convoluted approach as any time you add a new child content type you’ll have to modify your CAML query.
The answer lies with how the ContentTypeID is constructed in SharePoint. The ContentTypeID is a concatenation of parent child ContentTypeIDs, this is to say that a ContentTypeID is composed of its parent ContentTypeID post fixed with a it’s own identifier.
| Content Type | Parent Content Type | Content Type ID |
| System | 0x | |
| Item | System | 0×01 |
| Document | Item | 0×0101 |
| HR Document | Document | 0×0101002C3431777FFD0742A58D02ABC9C5FA62 |
| CV | HR Document | 0×0101002C3431777FFD0742A58D02ABC9C5FA6201 |
| Application Form | HR Document | 0×0101002C3431777FFD0742A58D02ABC9C5FA6202 |
Knowing this you can construct a CAML query that uses the <BeginsWith> select statement.
To return all Documents you can use the following query:
<Where>
<BeginsWith>
<FieldRef Name=’ContentTypeId’/>
<Value Type=’Text’>0×0101</Value>
</BeginsWith>
</Where>
To return all HR Documents you can use the following query:
<Where>
<BeginsWith>
<FieldRef Name=’ContentTypeId’/>
<Value Type=’Text’>0×0101002C3431777FFD0742A58D02ABC9C5FA62</Value>
</BeginsWith>
</Where>
You can find the ContentTypeID by going to Site Actions | Site Settings | Site Content Types, and select the parent content type you are interested in. In the URL you will see the ContentTypeID in the page URL. For example: