4

I've some seen some Javascript code containing CDATA. e.g. below which I copied from http://www.w3schools.com/xml/xml_cdata.asp

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

Note that I did a description contained on link above. However I could come to conclusion on when to decide to use the CDATA tag.

If anyone could help me understand the purpose of this tag and when to use it will be great.

Nil Pun
  • 17,035
  • 39
  • 172
  • 294

3 Answers3

7

In XHTML the content of script elements is treated as markup. So < and & have their usual special meaning. A CDATA block tells the parser to treat the content as text instead of markup, so you can say if x is less than y without the < being treated as the start of a tag.

Note that if you serve XHTML with a Content-Type of text/html then it will be treated as broken HTML and not as XML. I recommend avoiding XHTML - it is only useful if you have XML processors in your tool chain and munging it to play nicely with HTML parsers is unnecessary work. Just write HTML and be done with it.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

Simply we can say , we need CDATA part we need your document to parse as XML

PSR
  • 39,804
  • 41
  • 111
  • 151
  • I have read that but still doesn't answer my question. When should we use it and what's the purpose if Parser ignores it anyway. – Nil Pun Jul 17 '13 at 10:50
  • It isn't about the validator. It is about any XML parser, including browsers. (If you are serving XHTML as text/html so they aren't parsed in XML mode, why are you using XHTML?) – Quentin Jul 17 '13 at 10:50
0

CDATA has no meaning in HTML, but in XML it's used to handle characters such as angle brackets and ampersands. I use a CDATA block when I need to include JavaScript in my XSL Transforms.

Understanding what CDATA does will probably help you understand when to use it: "Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA." See also: What is CDATA in HTML?

Community
  • 1
  • 1
Mentatmatt
  • 515
  • 5
  • 13