2012-11-23 49 views
3

XML:XSLT選擇文本沒有孩子

<data><ph>Foo</ph>Bar</data>

XSL:

<xsl:output method="xml" indent="yes"/> 
<xsl:template match="/"> 
    <xsl:apply-templates select="data/ph"/> 
    <xsl:apply-templates select="data"/> 
</xsl:template> 
<xsl:template match="data/ph"> 
    <xsl:value-of select="."/> 
</xsl:template> 
<xsl:template match="data"> 
    <xsl:value-of select="."/> 
</xsl:template> 

當XSL在/數據選擇文本/與<xsl:template match="data"><xsl:value-of select="."/>它也是孩子選擇文本實體數據/ ph。我如何僅指向/ data /的文本,而不包括/ data/ph /的文本?

我的輸出應該是:FooBar,而不是FooFooBar。

回答

2

當XSL選擇在/data/<xsl:template match="data"><xsl:value-of select="."/>文本它也選擇在子實體data/ph文本 。我如何僅指向 /data/的文字,而不包括/data/ph/的文字?

使用:當前節點的

<xsl:copy-of select="text()"/> 

此副本中的所有文本節點孩子。

利用這種校正,整個轉化成爲

<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:template match="/"> 
     <xsl:apply-templates select="data/ph"/> 
     <xsl:apply-templates select="data"/> 
    </xsl:template> 

    <xsl:template match="data/ph"> 
     <xsl:value-of select="."/> 
    </xsl:template> 

    <xsl:template match="data"> 
     <xsl:copy-of select="text()"/> 
    </xsl:template> 
</xsl:stylesheet> 

,並且當所提供的XML文檔施加:

<data><ph>Foo</ph>Bar</data> 

有用,正確的結果產生

FooBar 
+0

完美,所以我重寫它爲: 的

+0

@ user1848612,歡迎您。 –