XSLT xsl:attribute example how to generate link href

The xsl:attribute instruction add an attribute to the parent element of the instruction in template. For example you have a source element contains title and url of a web page, you need to convert it to HTML a tag and reconstruct the url in the final HTML element.

Here is an example.

The source document contains document like this

 
<chapter title="Lucene Searching">
      <section type="internal" title="Lucene Scoring">
        <leaf title="How Lucene scoring works" seotitle="how-lucene-scoring-works">
        </leaf>
      </section>    
      <section type="terminal" title="" seotitle="">
        <leaf title="hello world" seotitle="how-lucene-scoring-works">
        </leaf>
      </section>
    </chapter>
 

The leaf node represents a hypertext link , we want to transform it to HTML a tag.

Here is the XSLT template for this element

 
     <xsl:template match="leaf">
         <li>
             <a>
                 <xsl:attribute name="href">
                     http://makble.com/<xsl:value-of select="@seotitle"/>
                </xsl:attribute>
              <xsl:value-of select="@title"/></a>
         </li>
     </xsl:template>
 

The following is wrong

 
     <xsl:template match="leaf">
         <li>
             <a href="http://makble.com/<xsl:value-of select="@seotitle"/>">
              <xsl:value-of select="@title"/></a>
         </li>
     </xsl:template>
 
 
lxml.etree.XSLTApplyError: xsl:attribute: Cannot add attributes to an element if children have been already added to the element.