DocbookのXMLから目次情報を抽出する toc.xsl の作成
今回は、Docbookで記述されたXML文書から目次情報だけを抽出してみます。
テストで処理対象としたXML文書は、 こちら(Apache Velocity DocBook Framework ) から入手できる DBFUserGuide.xml を使用します。これは、Docbook4.5を使って記述されています。
基本方針
ここでは、 Docbookに汎用で使用できる、というダイソレタことは考えません。 DBFUserGuide.xmlだけに有効な目次情報抽出用 xsl を記述します。 かなりシンプルなので、それぞれの状況に応用するのは簡単でしょう。
- book/title は目次に入れない
- chapter/title と chapter/section/title のテキスト部分を抽出して XMLを生成する
toc.xslの作成
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" indent="yes" encoding="UTF-8" />
<xsl:strip-space elements="*" />
<xsl:template match="*" />
<xsl:template match="book">
<list>
<xsl:apply-templates />
</list>
</xsl:template>
<xsl:template match="chapter">
<xsl:for-each select="title">
<item>
<xsl:value-of select="." />
</item>
</xsl:for-each>
<list>
<xsl:apply-templates select="section" />
</list>
</xsl:template>
<xsl:template match="chapter/section">
<xsl:apply-templates />
</xsl:template>
<xsl:template match="chapter/section/title">
<item>
<xsl:value-of select="." />
</item>
</xsl:template>
</xsl:stylesheet>
デフォルトの振る舞いを上書き
XSLTのデフォルトの振る舞いはすべてのノードを処理するようになっている。 今回は目次として表示するノードだけを出力したいので、 このデフォルトの振る舞いを以下のように上書きします。
<xsl:template match="*" />※すべてのノード処理を無効化
saxon を使って BDFUserGuide.xml を変換
saxonの用意
toc.xsl スタイルシートを使って変換するには、XSLTが必要です。今回は、saxon9 を使います。 http://saxon.sourceforge.net/から、saxonb9-1-0-5j.zip をダウンロードして、saxon/ 以下に展開しておきます。
toc.xsl を使って、 DBFUserGuide.xml → toc.xml に変換。
$ java -jar saxon/saxon9.jar -s:BDFUserGuide.xml -xsl:toc.xsl -o:toc.xml
Makefile
コマンドラインでの入力を省略するための Makefile.
saxon=saxon/saxon9.jar
stylesheet=toc.xsl
in=DBFUserGuide.xml
out=toc.xml
$(out) : $(in) $(stylesheet)
@java -jar $(saxon) -novw -s:$< -xsl:$(stylesheet) -o:$@
cat $@
clean :
@$(RM) $(out)
処理結果 toc.xml
<?xml version="1.0" encoding="UTF-8"?>
<list>
<item>Preface</item>
<list>
<item>About this Project</item>
<item>License Information</item>
<item>Author Information</item>
</list>
<item>Introduction</item>
<list>
<item>Why another framework for rendering docbook?</item>
<item>What you need</item>
<item>Caveat Emptor!</item>
</list>
<item>Using the Framework</item>
<list>
<item>How to set up your documentation files</item>
<item>Customizing your documentation file layout</item>
<item>Writing your documentation</item>
<item>Notes</item>
</list>
<item>Developer information</item>
<list>
<item>ant files</item>
<item>DocBook reference files</item>
<item>XML Resolver</item>
<item>Docbook Source files</item>
<item>Stylesheets and Driver files</item>
<item>StyleSheet customizations</item>
<item>PDF StyleSheet information</item>
<item>Titlepages</item>
</list>
<item>Acknowledgements</item>
<list/>
</list>
章番号、セクション番号を追加
このままでもFrameMakerへ読み込ませてEDD定義などを行えば、章番号・セクション番号追加できるのだが、 XSLTにもそれらを追加する機能があるので、 次回は番号を追加してみます。