Using XInclude to include example code in a DocBook file

I love DocBook! Any article, guide and resource I write for or any other publisher is first created as a DocBook file and stored in a Version Control System, usually Subversion or GIT.

Yesterday I was writing a technical article about ActiveSupport. Easy to understand, the article was full of Ruby examples and it was somehow the first time I had to include so many working examples in a single article. I started to collect them in a single folder organized by sections. The scripts needs to be executed and tested before being included into the article and TextMate is definitely more confortable than Oxygen for writing a Ruby script!

After a couple of minutes I realized that probably there was a better solution to include those files directly in the main article and I started looking at it. I just felt an idiot when I realized I could use XInclude in the same way I usually include different chapters in a DocBook book.

Here's the solution. To include an example code in your article first import the XInclude module in your DocBook file declaration, if you didn't before.


Then include the code as plain text with the <xi:include> tag. The following example includes the Ruby script stored in example.rb.

<programlisting language="ruby"><xi:include href="example.rb" parse="text" /></programlisting>

I usually wrap the script in a <programlisting> tag. For more complex examples you might want to use an <example> tag. Be sure to set the attribute parse to text or the processor will try to parse the content as an XML file.

For more details about the XInclude I suggest the Using XInclude article published by O'Reilly.