I am confused about the use of XSLT templates and when/how they are applied. Suppose I have the following XML file:
<book>
<chapter> 1 </chapter>
<chapter> 2 </chapter>
</book>
and I'd like to match all chapters in order. This is a XSLT stylesheet:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="book">
<h1>book</h1>
</xsl:template>
<xsl:template match="chapter">
<h2>chapter <xsl:value-of select="."/></h2>
</xsl:template>
</xsl:stylesheet>
The result of the stylesheet is
<h1>book</h1>
without the expected numeration of chapters. Adding an <xsl:apply-templates />
at the end of the book
matching template didn't help. I'd like to do without an xls:for-each
though.
EDIT I ought to have mentioned this: I'm using Python's lxml module which uses libxml2 and libxslt. The following code does not produce the expected result but instead the above:
import lxml.etree
xml = lxml.etree.XML("""
<book>
<chapter> 1 </chapter>
<chapter> 2 </chapter>
</book>
""")
transform = lxml.etree.XSLT( lxml.etree.XML("""
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="book">
<h1>book</h1>
<xsl:apply-templates />
</xsl:template>
<xsl:template match="chapter">
<h2>chapter <xsl:value-of select="."/></h2>
</xsl:template>
</xsl:stylesheet>
""") )
html = transform(xml)
print( lxml.etree.tostring(html, pretty_print=True) )
Oddly enough, the correct (expected) result is demonstrated here. Accessing libxslt
directly through the Python bindings instead of going through lxml works, however:
import libxml2
import libxslt
doc = libxml2.parseDoc("""
<book>
<chapter> 1 </chapter>
<chapter> 2 </chapter>
</book>
""")
styledoc = libxml2.parseDoc("""
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:template match="book">
<h1>book</h1>
<xsl:apply-templates />
</xsl:template>
<xsl:template match="chapter">
<h2>chapter <xsl:value-of select="."/></h2>
</xsl:template>
</xsl:stylesheet>
""")
style = libxslt.parseStylesheetDoc(styledoc)
print( style.applyStylesheet(doc, None) )
What am I missing?
book
\n\n`. That's the root of the confusion because I'd have expected to see the chapters too... – Jens Jan 31 '15 at 15:50