0
votes

I am using XSLT to transform XML before importing it into InDesign.

Some elements include text with a number of child elements that format for italics, bold, etc. To make the italics work in InDesign I want to add an attribute to these child elements.

Unfortunately, in my attempts so far, I can't figure out how to add the attribute to all these child elements while leaving them in the same position within the parent element.

So I want to take some XML that looks like this:

<copy_block>
    A section of text of an unknown length in which might appear <i>one or more</i> sections 
    of italics <i>which I want to add</i> an attribute to.
</copy_block>

and use my XSL stylesheet to transform it to:

<copy_block>
    A section of text of an unknown length in which might appear <i cstyle="stylename">one or more</i> sections 
    of italics <i cstyle="stylename">which I want to add</i> an attribute to.
</copy_block>

I don't think it can be that hard, but for some reason I am stumped. Any help would be very much appreciated.

Thank you!

1

1 Answers

0
votes

Start with the identity template

<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()" />
  </xsl:copy>
</xsl:template>

(In XSLT 3.0, you can replace this with just <xsl:mode on-no-match="shallow-copy"/>)

This deals with copying all elements and nodes unchanged. All you then need to do is add an overriding template that matches i that adds an attribute to it.

<xsl:template match="i">
  <i cstyle="stylename">
    <xsl:apply-templates />
  </i>
</xsl:template>

Try this full XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="i">
    <i cstyle="stylename">
      <xsl:apply-templates />
    </i>
  </xsl:template>
</xsl:stylesheet>

See it in action at http://xsltfiddle.liberty-development.net/nc4NzR2