2012-12-06 121 views
0

我是XSL的新手,我正在尋找一種方法來替換XML中的文本。 我的源XML是:XSLT文本替換

<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樣式表來管理呢?

在此先感謝!

+0

你已經試過了什麼? –

+1

這是屬於SO上類似的問題。 但是這將取代任何出現的字符串,而不僅僅是一個 ' < xsl:template match =「A/[key ='Two']/string/text()」> xxx ' – Fmessina

回答

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軸。 All available axes are documented here in the xpath specification

+0

是的!完美:) 非常感謝,我會看看建議的鏈接! – Fmessina