sanjay
sanjay

Reputation: 1020

XSLT - Add node before given node

I need to add new xml node before given node.

Example :

<doc>
  <a></a>
  <b></b>
  <c></c>
  <a></a>
  <d></d>
  <e></e>
  <a></a>
</doc>

I need to add new <n> node before every <a> node. so the output should be

<doc>
  <n></n>
  <a></a>
  <b></b>
  <c></c>
  <n></n>
  <a></a>
  <d></d>
  <e></e>
  <n></n>
  <a></a>
</doc>

I can add a new node inside given node or after given node. but I couldn't find a way to add new node before a given node.

Any idea how to do this?

Upvotes: 0

Views: 549

Answers (1)

Reinder Wit
Reinder Wit

Reputation: 6615

You can have a separate template that will match only a. In that template you can add the <n> node:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes" />
    <xsl:template match="/">
        <doc>
            <xsl:apply-templates select="doc/*"/>
        </doc>
    </xsl:template>
    <xsl:template match="a">
        <n></n>
        <a></a>
    </xsl:template>
    <xsl:template match="*">
        <xsl:element name="{local-name()}"></xsl:element>
    </xsl:template>
</xsl:stylesheet>

Upvotes: 1

Related Questions