Toolbox
Toolbox

Reputation: 2491

Add element after document has been produced

After having created an XHTML document using XSLT, I need to add an element (link:schemaRef).

The reason is that I am merging 2 XHTML document and it is only the merged document that should have the element I need to add. I reduced the length of the link just to fit the example better.

I cannot see that the result file has the added link. Something obviously wrong in my code?

My code base:

  <!-- Identity transform -->

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

  <!-- Find and add element in document -->

<xsl:template match="/xhtml:html/xhtml:body/xhtml:div[1]/ix:header/ix:hidden/ix:references">
   <xsl:copy>
     <xsl:copy-of select="@*" />
    <xsl:element name="link:schemaRef">
      <xsl:attribute name="xlink:type">simple</xsl:attribute>
      <xsl:attribute name="xlink:href">http://example.org</xsl:attribute>
    </xsl:element>
    <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

Upvotes: 0

Views: 54

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

You still haven't explained how your input looks but if you want to perform two transformations within one stylesheet then you can use modes to separate them plus store the first transformation step's result in a variable you push to the second mode:

<xsl:mode name="m1" on-no-match="shallow-copy"/>

<xsl:variable name="intermediary-result">
  <xsl:apply-templates mode="m1"/>
</xsl:variable>

<xsl:template match="/">
  <xsl:apply-templates select="$intermediary-result" mode="m2"/>
</xsl:template>

<xsl:mode name="m2" on-no-match="shallow-copy"/>

<xsl:template mode="m2" match="/xhtml:html/xhtml:body/xhtml:div[1]/ix:header/ix:hidden/ix:references">
   <xsl:copy>
     <xsl:copy-of select="@*" />
    <xsl:element name="link:schemaRef">
      <xsl:attribute name="xlink:type">simple</xsl:attribute>
      <xsl:attribute name="xlink:href">http://example.org</xsl:attribute>
    </xsl:element>
    <xsl:apply-templates mode="#current"/>
    </xsl:copy>
</xsl:template>

Upvotes: 1

Related Questions