使用基于param的XSLT更新元素的文本

use*_*518 6 xslt

我正在尝试做一些似乎应该非常简单的事情,但是我无法让它发挥作用,我似乎无法找到任何不涉及许多无关紧要的事情的例子.我想将特定xml标记的文本内容更新为特定值(作为参数传入,将从ant使用此XSLT).一个简单的例子:

我想改造

<foo>
  <bar>
    baz
  </bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

<foo>
    <bar>
        something different
    </bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

这是我试过的样式表,它只产生标签,根本没有文字

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <!-- identity transformation, to keep everything unchanged except for the stuff we want to change -->
    <!-- Whenever you match any node or any attribute -->
    <xsl:template match="node()|@*">
        <!-- Copy the current node -->
        <xsl:copy>
            <!-- Including any attributes it has and any child nodes -->
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <!-- change the text of the bar node, in the real template the value won't be specified inline -->
    <xsl:template match="/foo/bar/">
        <xsl:param name="baz" value="something different"/>
            <xsl:value-of select="$baz"/>
    </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Dim*_*hev 11

提供的代码存在许多问题,导致编译时错误:

<xsl:template match="/foo/bar/"> 
    <xsl:param name="baz" value="something different"/> 
        <xsl:value-of select="$baz"/> 
</xsl:template>
Run Code Online (Sandbox Code Playgroud)
  1. 此模板上指定的匹配模式在语法上是非法的 - XPath表达式不能以该/字符结尾.

  2. xsl:param 不能有一个未知的属性,如 value

方案:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pReplacement" select="'Something Different'"/>

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

 <xsl:template match="foo/bar/text()">
  <xsl:value-of select="$pReplacement"/>
 </xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)

在提供的XML文档上应用此转换时:

<foo>
  <bar>
    baz
  </bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

产生了想要的正确结果:

<foo>
   <bar>Something Different</bar>
</foo>
Run Code Online (Sandbox Code Playgroud)