Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xslt: add node to root element

Tags:

xml

xslt

i have simple XML file:

<MyRoot>
   <Value key="TARGET">foo</Value>
   <Value key="MODEL">bar</Value>
   <Value key="MANUFACTURER">bla</Value>
</MyRoot>

and i want to add a Value node to MyRoot using XSLT. I can't figure out how.

Result should be:

<MyRoot>
   <Value key="TARGET">foo</Value>
   <Value key="MODEL">bar</Value>
   <Value key="MANUFACTURER">bla</Value>
   <Value key="NEWNODE">yeahIMadeIt</Value>
</MyRoot>

What i have so far is:

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

But this puts the new Value node under the root Node :

<MyRoot>
   <Value key="TARGET">foo</Value>
   <Value key="MODEL">bar</Value>
   <Value key="MANUFACTURER">bla</Value>
</MyRoot>
<Value key="NEWNODE">yeahIMadeIt</Value>
like image 911
martin Avatar asked Jul 18 '11 15:07

martin


1 Answers

You're on the right track. You need to change your template match. Try:

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

<xsl:template match="MyRoot">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
        <Value key="NEWNODE">yeahIMadeIt</Value>
    </xsl:copy>
</xsl:template>
like image 54
dogbane Avatar answered Sep 25 '22 13:09

dogbane