0

我是 XSL 的新手,我正在寻找一种方法来替换 XML 中的文本。我的源 XML 是:

<A>
 <key>One</key>
 <string>value1</string>
 <key>Two</key>
 <string>value2</string>
 <key>Three</key>
 <string>value3</string>
</A>

我想要的是只替换其中一个元素。结果应该是:

<A>
 <key>One</key>
 <string>value1</string>  
 <key>Two</key>
 <string>xxx</string>  <---- change this (for key Two)
 <key>Three</key>
 <string>value3</string>
</A>

如何创建一个 xsl 样式表来管理它?

提前致谢!

4

1 回答 1

1

这似乎可以解决问题:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:template match="string">
    <xsl:choose>
      <xsl:when test="preceding-sibling::key[position() = 1 and text() = 'Two']">
        <string>replacement</string>
      </xsl:when>
      <xsl:otherwise>
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>  
      </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>  
    </xsl:template>
</xsl:stylesheet>

关键片段是preceding-sibling轴的使用。所有可用的轴都记录在 xpath 规范中。

于 2012-12-06T14:34:23.133 回答