XSLT Example: Add a new node to elements

How to add a new element to every child element of a certain parent?

For example, consider you want to add <type> element to the element under <library>. The <type> element should have the name of the element as the value.

<library>
  <book>
    <title>Programming Erlang</title>
    <author>Armstrong</author>
  </book>
  <magazine>
    <title>TAMIYA TOURING CAR</title>
  </magazine>
</library>

The resultant XML should look like this.

<?xml version="1.0"?>
<library>
  <book>
    <type>book</type>
    <title>Programming Erlang</title>
    <author>Armstrong</author>
  </book>
  <magazine>
    <type>magazine</type>
    <title>TAMIYA TOURING CAR</title>
  </magazine>
</library>

The following XSLT does the trick.

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

  <!-- If an element is a child of library, copy the content and add
       type element. -->
  <xsl:template match="library/*">
    <xsl:copy>
      <xsl:element name="type">
        <xsl:value-of select="name(.)"/>
      </xsl:element>

      <xsl:call-template name="copy-children"/>
    </xsl:copy>
  </xsl:template>

  <!-- Copy the children of the current node. -->
  <xsl:template name="copy-children">
    <xsl:copy-of select="./*"/>
  </xsl:template>

  <!-- Generic identity template -->
  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>
About these ads

About Moto

Engineer who likes coding
This entry was posted in Tips and tagged . Bookmark the permalink.

2 Responses to XSLT Example: Add a new node to elements

  1. Ewgenius says:

    hi you….

    can you help me?

    How can I add an element aoutomaticly like here

    I have created this element:

    how can I create now to the tr element an other tr for exaple….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s