We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

XInclude support in ElementTree 1.2

Aug 15, 2003 | Fredrik Lundh

ElementTree 1.2 provides limited support for XInclude directives, via the ElementInclude helper module. This module can be used to insert subtrees and text strings into element trees, based on information in the tree.

The XInclude extension defines two special elements:


This element is used to specify where data from another document should be included. You can include XML data (element hierarchies), or plain text.


This element is used to provide fallback data, in case an include operation fails.


To include a XML document in the current document, use the {http://www.w3.org/2001/XInclude}include element and set the parse attribute to “xml”, and use the href attribute to specify the document to include.

<document xmlns:xi="http://www.w3.org/2001/XInclude">
<xi:include href="source.xml" parse="xml" />

By default, the href attribute is treated as a file name. You can use custom loaders to override this behaviour. Also note that the standard helper does not support XPointer syntax.

To process this file, load it as usual, and pass the root element to the ElementTree module:

from elementtree import ElementTree, ElementInclude

tree = ElementTree.parse("document.xml")
root = tree.getroot()


The ElementInclude module replaces the {http://www.w3.org/2001/XInclude}include element with the root element from the source.xml document. The result might look something like this:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
<para>This is a paragraph.</para>

If the parse attribute is omitted, it defaults to “xml”. The href attribute is required.

To include a text document, use the {http://www.w3.org/2001/XInclude}include element, and set the parse attribute to “text”:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
Copyright (c) <xi:include href="year.txt" parse="text" />.

The result might look something like:

<document xmlns:xi="http://www.w3.org/2001/XInclude">
Copyright (c) 2003.


Include support is available in elementtree 1.2 alpha 3 and later.