开发者

Xslt: add node to root element

开发者 https://www.devze.com 2023-03-21 16:28 出处:网络
i have simple XML file: <MyRoot> <Value key=\"TARGET\">foo</Value> <Value key=\"MODEL\">bar</Value>

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="MANUFACT开发者_如何学运维URER">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>


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消