PCDATA - Parsed Character Data

PCDATA means parsed character data. For example:

<book>Yunus Emre Divani</book>

Inside the book element, special characters such as &, <, and > must be escaped as &amp;, &lt;, and &gt;. Otherwise, the XML parser may treat them as markup and throw an error.

When we need to keep this kind of content as raw text, we can use CDATA.

CDATA - Character Data

CDATA means character data. We use CDATA when PCDATA is not enough, especially when the content includes markup-like text.

<book>
	<![CDATA[
	Yunus <emre> Divani
	]]>
</book>

CDATA starts with <![CDATA[ and ends with ]]>. So where do we use it?

Scenario: imagine a news site where the headline, breaking news, exchange rates, and sports results need to be updated instantly. How can we manage those updates with XML?

First, let's list the areas that need to be updated:

  • Site Title
  • Breaking News
  • Headline
  • Exchange Rates
  • Sports Results

Now let's create XML that fits this structure.

<?xml version="1.0" encoding="UTF-8"?>
<site update="01.01.2015 12:15">
	<head>
		<title></title>
	</head>
	<body>
		<headline></headline>
		<breaking></breaking>
		<currency></currency>
		<sports></sports>
	</body>
</site>

After creating the tree structure above, we may get an error if we add HTML directly into fields such as the headline.

CDATA solves this problem by letting us keep the HTML-like content as character data.

<?xml version="1.0" encoding="UTF-8"?>
<site update="01.01.2015 12:15">
	<head>
		<title>Breaking News - News</title>
	</head>
	<body>
		<headline>
			<![CDATA[
			<li><img src="firstcar.jpg"></li>
			<li><img src="firstplane.jpg"></li>
			<li><img src="firstsatellite.jpg"></li>
			]]>
		</headline>
		<breaking>
			<![CDATA[
			<li>The first national vehicle powered by boron was produced.</li>
			<li>The first national aircraft was tested by the prime minister.</li>
			<li>The first national satellite was launched by TUBITAK from Kirsehir.</li>
			]]>
		</breaking>
		<currency>
			<![CDATA[
			<div class="dollar">
				x.xxxx
			</div>
			<div class="euro">
				x.xxxx
			</div>
			<div class="bist">
				x.xxxx
			</div>
			]]>
		</currency>
		<sports>
			<![CDATA[
			<li>Incredibly talented kid.</li>
			<li>Shake-up in Galatasaray management.</li>
			<li>Shock transfer to Fenerbahce.</li>
			<li>Sponsorship deal from Besiktas.</li>
			]]>
		</sports>
	</body>
</site>

During update operations, you can parse the XML data and update the relevant sections quickly.