XSLT: Generate heading from WordProcessingML

Microsoft Word (and WordProcessingML) treats all paragraphs equally (all of the are represented as w:p elements) and it's the job of the XSLT programmer to separate headings (the paragraphs where the paragraph style contains w:pPr/w:outlineLvl/@w:val) from the regular text.

I've started by defining a key that would extract the outline level from the paragraphs style associated with the current w:p element:
<xsl:key name="outline" match="w:outlineLvl" use="ancestor::w:style[@w:type = 'paragraph']/@w:styleId" />
If successful, this key would return the w:outlineLvl element whose ancestor w:style element has the specified w:styleId attribute (and, yes, it took me five minutes to figure out what I've been doing when I've revisited the code after three months). The key is then used in a template that uses xsl:element to create a Hx or P element:
<xsl:template match="w:p">
  <xsl:variable name="paraStyle" select="w:pPr/w:pStyle/@w:val" />
  <xsl:variable name="outLvl"
    select="key('outline',w:pPr/w:pStyle/@w:val)/@w:val" />
  <xsl:variable name="elName">
    <xsl:choose>
      <xsl:when test="$outLvl">h<xsl:value-of select="$outLvl + 1" /></xsl:when>
      <xsl:otherwise>p</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:element name="{$elName}">
... rest of translation code ...
  </xsl:element>
</xsl:template>

No comments:

Post a Comment