Open In App

How to Escape Ampersands in XML to Rendered as Entities ?

Last Updated : 06 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Extensible Markup Language(XML) is widely used for storing and exchanging structured data. It requires proper character escaping to ensure special characters like ampersands (&) are correctly interpreted by XML parsers.

The ampersand (&) is a special character in XML used to begin entity references. To treat it as data, it must be escaped as “&”. This preserves its intended meaning while maintaining XML structure. Correctly escaping ampersands is vital when working with XML documents containing URLs or text with ampersands. Failure to do so can lead to parsing errors or invalid XML. XML parsers interpret entity references to restore the original characters. Using the “&” entity reference ensures that the ampersand is rendered correctly and not mistakenly interpreted as an entity or tag.

Syntax:

&

Approach 1: Using XML Entity Reference involves representing special characters or reserved symbols in XML using predefined entities like & for the ampersand, < for less-than, > for greater-than, etc.

Example: The XML code represents a document with a root element called “root” that has three child elements: “title,” “text,” and “styledText.” The title element contains the text “Geeksforgeeks!!,” while the text and styledText elements display the phrase “Escape ampersands: A &amp;amp; B” using XML escaping for the ampersand character.

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<root>
    <title>
          Geeksforgeeks!!
      </title>
    <text>
          Escape ampersands: A &amp; B
      </text>
    <styledText>
          Escape ampersands: A &amp; B
      </styledText>
</root>


Output:

Screenshot-(209).png

Approach 2: CDATA (Character Data) sections are used to escape blocks of text that may contain special characters or reserved characters in XML.

Example: The XML code shows a titled “Geeksforgeeks!!” with a description containing computer science and programming articles, including the use of “&amp;”.

XML




<?xml version="1.0" encoding="UTF-8"?>
<book>
    <title>
          Geeksforgeeks!!
      </title>
    <description>
        <![CDATA[It contains well written, 
        well thought and well explained computer science
        & programming articles.]]>
    </description>
</book>


Output:

How-do-I-escape-ampersands-in-XML-so-they-are-rendered-as-entities-in.png



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads