2015-11-17 103 views
0

我有這樣的XML替換文本()節點的具體內容,XSLT - 用新節點

<doc> 
    <p>Biological<sub>89</sub> bases<sub>4456</sub> for<sub>8910</sub> sexual<sub>4456</sub> 
      differences<sub>8910</sub> in<sub>4456</sub> the brain exist in a wide range of 
     vertebrate species, including chickens<sub>8910</sub> Recently<sub>8910</sub> the 
      dogma<sub>8910</sub> of<sub>4456</sub> hormonal dependence for the sexual 
     differentiation of the brain has been challenged.</p> 
</doc> 

正如你可以看到有<sub>節點和text()節點包含<p>節點內。並且每個<sub>節點結束,都有一個以空格開始的文本節點。 (例如:<sub>89</sub> bases:此處出現'bases'文本之前存在空格)。我需要用節點替換這些特定空格。

SO預期的輸出應該是這樣的,

<doc> 
    <p>Biological<sub>89</sub><s/>bases<sub>4456</sub><s/>for<sub>8910</sub><s/>sexual<sub>4456</sub> 
     <s/>differences<sub>8910</sub><s/>in<sub>4456</sub><s/>the brain exist in a wide range of 
     vertebrate species, including chickens<sub>8910</sub><s/>Recently<sub>8910</sub><s/>the 
     dogma<sub>8910</sub><s/>of<sub>4456</sub><s/>hormonal dependence for the sexual 
     differentiation of the brain has been challenged.</p> 
</doc> 

要做到這一點,我可以使用正則表達式這樣,

<xsl:template match="p/text()"> 
     <xsl:analyze-string select="." regex="(&#x20;)"> 
      <xsl:matching-substring> 
       <xsl:choose> 
        <xsl:when test="regex-group(1)"> 
         <s/> 
        </xsl:when>     
       </xsl:choose> 
      </xsl:matching-substring> 
      <xsl:non-matching-substring> 
       <xsl:value-of select="."/> 
      </xsl:non-matching-substring> 
     </xsl:analyze-string> 
    </xsl:template> 

但是這會增加<s/>節點的每一個空間的文本( )節點。但我只需要添加節點到特定的空間。

任何人都可以給我建議的方法我怎麼能做到這一點..

回答

2

如果你只想匹配以空格開始,由sub元素被前面文本節點,你可以把你的模板條件匹配

<xsl:template match="p/text()[substring(., 1, 1) = ' '][preceding-sibling::node()[1][self::sub]]"> 

如果你只是想t o刪除字符串開頭處的空格,一個簡單的替換就可以了。

<xsl:value-of select="replace(., '^\s+', '')" /> 

試試這個XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
    <xsl:output method="xml" indent="no" /> 

    <xsl:template match="p/text()[substring(., 1, 1) = ' '][preceding-sibling::node()[1][self::sub]]"> 
     <s /> 
     <xsl:value-of select="replace(., '^\s+', '')" /> 
    </xsl:template> 

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

只要改變正則表達式,像這樣^(&#x20;):它會在文本部分的開頭只匹配的空間。

有了這個XSL剪斷:

<xsl:analyze-string select="." regex="^(&#x20;)"> 

這是我得到的結果:

<p>Biological<sub>89</sub><s></s>bases<sub>4456</sub><s></s>for<sub>8910</sub><s></s>sexual<sub>4456</sub> 
     differences<sub>8910</sub><s></s>in<sub>4456</sub><s></s>the brain exist in a wide range of 
     vertebrate species, including chickens<sub>8910</sub><s></s>Recently<sub>8910</sub><s></s>the 
     dogma<sub>8910</sub><s></s>of<sub>4456</sub><s></s>hormonal dependence for the sexual 
     differentiation of the brain has been challenged. 
     </p>