CDATA Element in SVG

CDATA is Character Data are used to escape blocks of text containing characters which would otherwise be recognized as markup in XHTML

CDATA Element

CDATA is known as Character Data is used to escape blocks of text containing characters that would otherwise be recognized as markup in XHTML.

Syntax

The above syntax is composed of three sections, that are

  • CDATA Start: CDATA begins with the nine-character delimiter <![CDATA[
  • CDATA End: CDATA section ends with ]]> delimiter.
  • CData Body: Characters between these two enclosures are interpreted as characters, and not as markup. This section may contain markup characters (<, >, and &), but they are ignored by the XML processor.

Example

The following markup code shows an example of CDATA. Here, the parser ignores every character written inside the CDATA section.

In the above example, everything between <message> and </message> is treated as character data and not markup.

Why CDATA Element is used for?

CDATA is normally used in svg as the parent element of the contents of the <style> and <script> element. Predefined entities such as <, >, and & Typing is required and often difficult to read in a markup. In such cases, the CDATA section can be used. Using the CDATA section, you instruct the parser that the particular section of the document has no markup and should be treated as plain text.

If we want to use CDATA, we have to follow few rules for XML CDATA, that are

  • CDATA cannot contain the string "]]>" anywhere in the XML document.
  • Nesting is not allowed in CDATA section.
Since CDATA is an XML(Extensible Markup Language) thing, it's deprecated in HTML and is rendered as a comment which only displays"]]>" as the output. But it still works as a parent to an <svg> style/script element contents.

The elements used in CDATA are:

  • <style> Elemrnt
  • <script> Element

<style> tag 

The <style> svg element is used to embed style informations in an svg element. The following below code shows how to include CSS internal styling to an SVG Element.

Note how CSS defined the presentation attributes. The SVG <style> element is NOT supported in Internet Explorer phone.

<script> tag

The <script> SVG element is used to embed internal scripting in an SVG element. The below code shows how to create an ellipse using pure JavaScript.

Note the use of "getElementNS("svgNS_URI", "qualified name of the element to create")" where NS means NameSpace and svgNS_URI means the SVG NameSpace Uniform Resource Identifier which specifies a link to the SVG namespace to be used, in this case, "http://www.w3.org/2000/svg". If the namespace URI was not specified, JavaScript cannot create the Element.

Although the script and style elements are embedded in SVG, they still have a global scope in the entire document.