I am confused about using XSLT templates and when / how they apply. Suppose I have the following XML file:
<book>
<chapter> 1 </chapter>
<chapter> 2 </chapter>
</book>
and I would like to fit all the chapters in order. This is the 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>
Style Sheet Result
<h1>book</h1>
without the expected numbering of chapters. Adding a <xsl:apply-templates />matching pattern at the end bookdid not help. I would like to do without xls:for-each.
EDIT I should have mentioned this: I am using the Python lxml module , which uses libxml2 and libxslt . The following code does not produce the expected result, but instead:
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) )
, () . libxslt Python lxml:
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) )
?