Dtd Entities in XML
DTD Entities in XML
What are Entities in DTD?
Entities are reusable pieces of text or data defined in a DTD.
They act like variables or macros that can be referenced multiple times in an XML document.
Entities help avoid repetition and make documents easier to maintain.
Types of Entities
| Type | Description | Syntax Example |
|---|---|---|
| Internal Entity | Defined directly with replacement text | <!ENTITY name "replacement text"> |
| External Entity | References external resource or file | <!ENTITY name SYSTEM "URI_or_file_path"> |
| Parameter Entity | Used inside DTD, starts with % | <!ENTITY % name "replacement"> |
1. Internal Entities
Replace a name with a specific string or text.
Useful for special characters or repeated strings.
Example:
<!ENTITY author "John Smith"><!ENTITY copy "© 2025 My Company">In XML, you can use:
<book> <author>&author;</author> <copyright>©</copyright></book>2. External Entities
Reference external files or data.
Can be included in the XML content.
Example:
<!ENTITY logo SYSTEM "http://example.com/logo.png">You can reference it in XML as &logo;.
3. Parameter Entities
Used within the DTD itself to simplify or reuse parts of the DTD.
Always prefixed with
%.Not used directly inside XML documents.
Example:
<!ENTITY % commonAttrs 'id ID #REQUIRED name CDATA #IMPLIED'><!ATTLIST book %commonAttrs;>This includes the attributes defined in %commonAttrs into the <book> element's attribute list.
How to Use Entities in XML
Entities are referenced with an ampersand
&and semicolon;.
&entityName;For example:
&author;will be replaced with"John Smith"if defined as above.
Summary Table
| Entity Type | Use Case | Syntax Example | Usage in XML |
|---|---|---|---|
| Internal Entity | Reusable text or characters | <!ENTITY author "John Smith"> | &author; |
| External Entity | Refer external files/data | <!ENTITY logo SYSTEM "logo.png"> | &logo; |
| Parameter Entity | Reuse DTD fragments | <!ENTITY % commonAttrs 'id ID #REQUIRED'> | Used inside DTD only |
Simple DTD Example Using Entities
<!ENTITY company "Acme Corp."><!ENTITY % standardAttrs 'id ID #REQUIRED'><!ELEMENT book (title, author)><!ATTLIST book %standardAttrs;><!ELEMENT title (#PCDATA)><!ELEMENT author (#PCDATA)>And in XML:
<book id="b001"> <title>XML Fundamentals</title> <author>&company;</author></book>If you want, I can help create a full example showing how to define and use entities effectively!