xml Entities External parsed entities


Example

XML fragments, also known under the name of external parsed entities, can be stored in separate files.

XML fragments, unlike XML documents, are less restrictive, in that several elements can appear top-level, as well as text nodes. Like an XML document, an external parsed entity may begin with an XML declaration, but this declaration is not considered part of its replacement text.

This is an example of external parsed entity:

<?xml version="1.0" encoding="UTF-8"?>
This is some text
<element/>
<element/>

An external parsed entity can then be declared in an XML document, in the DTD, and it can be used with an entity reference, which has the same syntax as for general internal entities:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY fragment SYSTEM "fragment.xml">
]>
<root>
    &fragment;
</root>

With the entity reference resolved, this document is equivalent to:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE root [
<!ENTITY fragment SYSTEM "fragment.xml">
]>
<root>
  This is some text
  <element/>
  <element/>
</root>

Every opening element tag in an external parsed entity must have a corresponding ending tag: it is not allowed to spread single elements over multiple entities, nor to spread markup.

A validating parser is required to resolve the entity reference and include its replacement text in the document as above. A non-validating parser may skip this, and instead tell the consuming application that there is an unresolved reference to an external parsed entity.