Skip to content

DTD Entities

Entities in DTDs are like variables or macros used to define shortcuts for frequently used text or special characters.

They help improve maintainability (change the value in one place) and readability.

Entities can be declared internally within the DTD or externally in a separate file.

  • &lt; represents < (less than)
  • &gt; represents > (greater than)
  • &amp; represents & (ampersand)
  • &quot; represents " (double quote)
  • &apos; represents ' (single quote/apostrophe)

You typically use these pre-defined entities when you need to include these characters as literal text within element content or attribute values, rather than having them interpreted as markup.

An internal entity associates a name with a replacement text string directly within the DTD.

`<!ENTITY entity-name "replacement text">`

DTD Declaration (can be internal or part of an external DTD file):

<!ENTITY writer "John Doe">
<!ENTITY copyright "Copyright (C) 2024 Example Inc.">
<!ENTITY company "Example Inc.">

XML Usage:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE document [
<!ELEMENT document (author, notice)>
<!ELEMENT author (#PCDATA)>
<!ELEMENT notice (#PCDATA)>
<!ENTITY writer "John Doe">
<!ENTITY copyright "Copyright (C) 2024 Example Inc.">
]>
<document>
<author>Written by &writer;.</author>
<notice>&copyright;</notice>
</document>

When parsed, &writer; will be replaced by “John Doe” and &copyright; by “Copyright (C) 2024 Example Inc.”.

Note: An entity reference consists of an ampersand (&), the entity name, and a semicolon (;).

An external entity associates a name with content located in an external resource (typically a file).

`<!ENTITY entity-name SYSTEM "URI/URL">`

Assume you have a file footer.xml containing:

<legal>All rights reserved by Example Inc. Use is subject to license terms.</legal>

DTD Declaration:

<!ENTITY footerContent SYSTEM "footer.xml">

XML Usage:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE report [
<!ELEMENT report (title, content, footer)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT content (#PCDATA)>
<!ELEMENT footer ANY> <!-- Define footer element -->
<!ENTITY footerContent SYSTEM "footer.xml"> <!-- Declare external entity -->
]>
<report>
<title>Annual Report</title>
<content>This year's performance was strong...</content>
<footer>&footerContent;</footer> <!-- Reference the external entity -->
</report>

When the XML parser processes this document, it will fetch the content of footer.xml and insert it where &footerContent; appears. Note that external entities can pose security risks (e.g., XML External Entity - XXE attacks) if the parser is not configured securely, especially when processing untrusted XML documents. Modern parsers often disable external entity processing by default.