我试图做一些事情,似乎应该是很简单的,但我不能得到它的工作,我似乎无法找到不涉及很多不相干的事情任何例子。 我想更新一个特定的XML标签的文本内容为特定值(传过来的参数,这个XSLT将蚂蚁使用)。 一个简单的例子:
我想改造
<foo>
<bar>
baz
</bar>
</foo>
至
<foo>
<bar>
something different
</bar>
</foo>
这是我试过的样式表,这将导致在短短的标签,没有任何文字
<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>
提前致谢!
有许多与所提供的代码问题,从而导致编译时错误:
<xsl:template match="/foo/bar/"> <xsl:param name="baz" value="something different"/> <xsl:value-of select="$baz"/> </xsl:template>
此模板中指定的匹配图案在语法上是非法- XPath表达式不能与结束/
字符。
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>
当这种转化应用所提供的XML文档:
<foo>
<bar>
baz
</bar>
</foo>
在想,正确的结果产生 :
<foo>
<bar>Something Different</bar>
</foo>
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output indent="yes" encoding="UTF-8" method="xml"/>
<xsl:param name="param-from-ant" as="xs:string"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="/foo/bar">
<xsl:value-of select="$param-from-ant"/>
</xsl:template>
</xsl:stylesheet>
稍微不同的方法:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="replace"/>
<xsl:template match="node()|@*">
<xsl:choose>
<xsl:when test="text() and name(..)='bar' and name(../..)='foo'">
<xsl:value-of select="$replace"/>
</xsl:when>
<xsl:otherwise>
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:otherwise>
</xsl:choose>
</xsl:template>