替换单个节点的值

时间:2014-12-02 18:00:47

标签: xslt xslt-2.0

假设我有这个输入文件

<root>

    <keyword>
        <name>foo</name>
        <value>bar</value>
    </keyword>
    <keyword>
        <name>123</name>
        <value>456</value>
    </keyword>

</root>

我想要这个输出:

<root>

    <keyword>
        <name>foobar</name>
        <value>bar</value>
    </keyword>
        <keyword>
        <name>123</name>
        <value>456</value>
    </keyword>

</root>

现在,我有这个有效的转型,但我想知道如何让它更优雅。

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  >

    <!-- copy all nodes and attributes -->
    <xsl:template match="@*|node()" name = "identity">
        <xsl:copy >
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match = "/root/keyword/name[text() = 'foo']">
        <name>foobar</name>
    </xsl:template>

</xsl:stylesheet>

匹配所需节点后,我再次重复设置,而不是简单地替换它。我可以更优雅地做到这一点吗?我的要求可能听起来有些荒谬,但我想更深入地了解xslt并更好地理解。

非常感谢!

2 个答案:

答案 0 :(得分:3)

假设XSLT 2.0,我会这样做(在http://xsltransform.net/3NzcBsW在线):

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"  >

    <xsl:param name="old" select="'foo'"/>
    <xsl:param name="new" select="'foobar'"/>

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

    <xsl:template match="/root/keyword/name[. = $old]">
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <xsl:value-of select="$new"/>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

参数看起来更灵活。除此之外,我没有看到缩短它的方法,身份转换模板是转换的核心,并且特定于输入XML示例的一个模板确保我们正在寻找的name元素获得新的内容。

答案 1 :(得分:0)

XSLT 2.0更短的方式:

 FAIL  src/test.test.js
  ● Test suite failed to run

    /Users/hannahmccain/Desktop/DEV/expense-report/fullstack-expense-report/client/src/node_modules/user/LoginContainer.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import React, { Component } from 'react'
                                                                                             ^^^^^^

    SyntaxError: Unexpected token import

      at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
      at Object.<anonymous> (src/index.js:11:164)
      at Object.<anonymous> (src/test.test.js:3:14)
相关问题