Answered Adding new node to xml as a first child using xslt

  • Sunday, December 02, 2012 2:56 PM
     
     

    Hi,

    I am new to xslt. Below is my Xml:

    <root id=1 name=abc>

    <child position=1>

    ...........

    </child>

    <child position=2>

    -------

    </child>

    <child position=3>

    -------

    </child>

    </root>

    I would like to add a new node between <root> and <child position=1> as below using xslt.

    <root id=1 name=abc>

    <new node>

    ---------

    </new node>

    <child position=1>

    ...........

    </child>

    <child position=2>

    -------

    </child>

    <child position=3>

    -------

    </child>

    </root>

    Can any body  help me?

All Replies

  • Sunday, December 02, 2012 5:14 PM
     
     Answered

    Write a template for "root" that creates a shallow copy and copies the attribute node, inserts the new node and copies the child nodes e.g.

      <xsl:template match="root">

         <xsl:copy>

            <xsl:copy-of select="@*"/>

            <new_node>...</new_node>

            <xsl:copy-of select="node()"/>

        </xsl:copy>

      </xsl:template>


    MVP Data Platform Development My blog

    • Proposed As Answer by Martin Honnen Sunday, December 02, 2012 6:10 PM
    • Marked As Answer by Dudy_22 Tuesday, December 04, 2012 7:19 PM
    •  
  • Monday, December 03, 2012 3:43 PM
     
     

    Thanks a lot..It's perfect code...

  • Tuesday, December 11, 2012 6:29 PM
     
     

    Hi,

    In the above xml I have to remove the ab from name attribute.

    the output should be

    <root id=1 name=c>

    <new node>

    ---------

    </new node>

    <child position=1>

    ...........

    </child>

    <child position=2>

    -------

    </child>

    <child position=3>

    -------

    </child>

    </root>

    Can any body  help me?

  • Tuesday, December 11, 2012 6:37 PM
     
     

    Please, next time, for a new question start a new thread.

    If you want to do more manipulations then it is best to write templates for the different tasks e.g.

    <xsl:template match="@* | node()">

      <xsl:copy>

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

      </xsl:copy>

    </xsl:template>

    <xsl:template match="root">

      <xsl:copy>

         <xsl:apply-templates select="@*"/>

          <new_node>...</new_node>

          <xsl:apply-templates/>

      </xsl:copy>

    </xsl:template>

    <xsl:template match="root/@name">

      <xsl:attribute name="{name()}">

        <xsl:value-of select="translate(., 'ab', '')"/>

       </xsl:attribute>

    </xsl:template>


    MVP Data Platform Development My blog