donderdag, juli 05, 2007

CAML and strange characters like '&'

Some day, my Caml Query failed with this exception:
"The property Query contains an invalid value."

The CAML XML:

<pre>
<Where>
<Eq>
<FieldRef Name='Summary'/><Value Type='Text'>jeroen & doreen></Value>
</Eq>
</Where>


I noticed the & and found out that the & character was the problem. Changing it into the encoded & gave the same problem... Thx to JOPX's connections in the Sharepoint world (of art;-) ) someone gave me a tip: try it with CDATA.....

So I check that out........ and it worked!!

So you need to put a CDATA tag around the text that can contain strange characters:


My new correct working CAML XML look like this:

<Where>
<Eq>
<FieldRef Name='Summary'/>
<Value Type='Text'> <![CDATA[jeroen & doreen]]> </Value>
</Eq>
</Where>


Some more info about CDATA:
Source: http://www.w3schools.com/
A CDATA section starts with "<![CDATA[" and ends with
"]]>":

<script>
<![CDATA[
function matchwo(a,b)
{
if (a < b && a < 0) then
{
return 1
}
else
{
return 0
}
}
]]>
</script>


In the example above, everything inside the CDATA section is ignored by
the parser.

Notes on CDATA sections:
A CDATA section cannot contain the string "]]>", therefore, nested CDATA sections are not allowed. Also make sure there are no spaces or line breaks inside the "]]>" string.