2011-08-02 23 views
2

考慮到這個XML代碼:如何保持和逃避無與倫比的元素?

<root> 
blah <foo>blah</foo> blah <bar>blah</bar> blah 
</root> 

而他相關的樣式表:

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

    <xsl:output omit-xml-declaration="yes"/> 

    <xsl:template match="foo"> 
     <strong><xsl:apply-templates/></strong> 
    </xsl:template> 

</xsl:stylesheet> 

與XSLTProcessor中類(PHP)transofrmation後,這裏是輸出:

blah <strong>blah</strong> blah blah blah 

但我而是想要這個輸出(樣式表中的未知元素被轉義):

blah <strong>blah</strong> blah &lt;bar&gt;blah&lt;/bar&gt; blah 

我建議僞代碼:

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

    <xsl:output omit-xml-declaration="yes"/> 

    <xsl:template match="foo"> 
     <strong><xsl:apply-templates/></strong> 
    </xsl:template> 

    <xsl:template match="all elements other than foo (with their attributs :p)"> 
     <xsl:copy-of select="node()" escape="yes"/> 
    </xsl:template> 

</xsl:stylesheet> 

我絕望了,所以如果你有保持和逃避那些無用的元素的任何解決方案,我會很高興!

回答

1
<?xml version="1.0"?> 
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:output omit-xml-declaration="yes"/> 

    <xsl:template match="root"> 
     <xsl:apply-templates/> 
    </xsl:template> 

    <xsl:template match="foo"> 
     <strong><xsl:value-of select="."/></strong> 
    </xsl:template> 

    <xsl:template match="*"> 
     <xsl:text>&lt;</xsl:text> 
      <xsl:value-of select="local-name(.)"/> 
      <xsl:apply-templates select="@*"/> 
     <xsl:text>&gt;</xsl:text> 

     <xsl:apply-templates select="node()"/> 

     <xsl:text>&lt;/</xsl:text> 
      <xsl:value-of select="local-name(.)"/> 
     <xsl:text>&gt;</xsl:text> 
    </xsl:template> 

    <xsl:template match="@*"> 
     <xsl:text>&#160;</xsl:text> 
     <xsl:value-of select="name()" /> 
     <xsl:text>="</xsl:text> 
     <xsl:value-of select="." /> 
     <xsl:text>"</xsl:text> 
    </xsl:template> 

    <xsl:template match="comment()"> 
     <xsl:text>&lt;!--</xsl:text> 
     <xsl:value-of select="."/> 
      <xsl:text>--&gt;</xsl:text> 
    </xsl:template> 

    <xsl:template match="processing-instruction()"> 
     <xsl:text>&lt;? </xsl:text> 
     <xsl:value-of select="name()"/> 
     <xsl:text>&#160;</xsl:text> 
     <xsl:value-of select="."/> 
      <xsl:text>?&gt;</xsl:text> 
    </xsl:template> 
</xsl:stylesheet> 
+0

以及感謝,它的工作原理!但它不是原始元素的真正轉義副本,更像是「重建」。例如,如果元素是' blah',則輸出將是'> blah'。 – Ayell

0

寫到這了我的頭頂部,所以請不要可以引用我這句話:d

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

    <xsl:output omit-xml-declaration="yes"/> 

    <xsl:template match="root"> 
     <xsl:apply-templates/> 
    </xsl:template> 

    <xsl:template match="foo"> 
     <strong><xsl:value-of select="."/></strong> 
    </xsl:template> 

    <xsl:template match="node()"> 
     &lt;<xsl:value-of select="local-name(.)"/>&gt;<xsl:value-of select="."/>&lt;/<xsl:value-of select="local-name(.)"/>&gt; 
    </xsl:template> 

</xsl:stylesheet>