View Single Post
Join Date: Oct 2008
Posts: 95
Reputation: fpmurphy is an unknown quantity at this point 
Solved Threads: 5
fpmurphy fpmurphy is offline Offline
Junior Poster in Training

Re: Adding New Element using XSLT

 
0
  #2
Jan 12th, 2009
Here is a simple example of adding an element. Suppose you have the folllowing XML document
XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. <root>
  2. <list>
  3. <a>aaaa</a>
  4. <b>bbbb</b>
  5. </list>
  6. </root>
and you want to add an extra element <c>. The following stylesheet is one way of adding this element.
XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" >
  2. <xsl:param name="ename">c</xsl:param>
  3. <xsl:param name="evalue">cccc</xsl:param>
  4.  
  5. <xsl:output method="xml" encoding="utf-8"/>
  6.  
  7. <xsl:template match="@*|node()">
  8. <xsl:copy>
  9. <xsl:apply-templates select="@*|node()" />
  10. </xsl:copy>
  11. </xsl:template>
  12.  
  13. <xsl:template match="list">
  14. <xsl:copy>
  15. <xsl:apply-templates/>
  16. <xsl:if test="not(c)">
  17. <xsl:element name="{$ename}"><xsl:value-of select="$evalue"/></xsl:element>
  18. </xsl:if>
  19. </xsl:copy>
  20. </xsl:template>
  21.  
  22. </xsl:stylesheet>
The output is
XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. <root>
  2. <list>
  3. <a>aaaa</a>
  4. <b>bbbb</b>
  5. <c>cccc</c></list>
  6. </root>
Reply With Quote