2013-05-14 49 views
0

輸入XML:輸出逃脫XML中的屬性在XSLT

<Parent> 
    <Child attr="thing">stuff</Child> 
</Parent> 

XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
    <xsl:template match="Child"> 
     <newChild chars="{..}" /> 
    </xsl:template> 
</xsl:stylesheet> 

期望otuput:所述 '字符' 的

<newChild chars="&lt;Child attr=&quot;thing&quot;&gt;stuff&lt;/Child&gt;" /> 

注意,值屬性就是'Child'標籤的轉義版本。

問題:如何獲取當前匹配的元素到屬性中?我雖然..通常會這樣做,但似乎不談論屬性時,我只是得到一些隨機的XML實體後跟Child值的值,例如<newChild chars="&#xA; stuff&#xA;"/>。我期待可能需要一些逃脫的東西來使其有效。

任何建議表示讚賞。

+0

AFAIK沒有一種簡單的或內置的方法來轉義輸出中的XML節點樹,但幸運的是有一種方法可以做到這一點,不會涉及到:http://stackoverflow.com/a/1162495/ 1945651 – JLRishe 2013-05-14 15:20:49

回答

0

它看起來像你必須建立這件事位(之前每個人都問,爲什麼我願意做這樣的事,我被我連接到應用程序的API限制)一點點。 請注意,..指向父。你想可能需要創建"&lt;Child attr=&quot;",追加<value-of select='@attr'/>"&gt;"<value-of select="."/>"&lt;/Child>",串聯所有的人,並使用一張字符屬性<xsl:attribute/>

喜歡的東西:

<newChild > 
    <xsl:attribute name="chars">&lt;Child attr=&quot;<xsl:value-of select="@attr"/>"&gt;"<value-of select="."/>&lt;/Child&gt;</xsl:attribute> 
    </newChild> 

沒有檢查,但希望它幫助。

但是它很容易出錯。如果我必須這樣做,我可能不會使用XSLT,而是一個具有「toXML()」方法的DOM,並在其上運行escapeXML()。

0

這裏是由JLRishe提到的解決方案的適應。

<?xml version="1.0" encoding="UTF-8"?> 
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:output omit-xml-declaration="yes" indent="yes"/> 
    <xsl:strip-space elements="*"/> 

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

    <xsl:template match="@*" mode="asEscapedString"> 
     <xsl:text> </xsl:text> 
     <xsl:value-of select="name()"/> 
     <xsl:text disable-output-escaping="yes"><![CDATA[=&quot;]]></xsl:text> 
     <xsl:value-of select="."/> 
     <xsl:text disable-output-escaping="yes"><![CDATA[&quot;]]></xsl:text> 
    </xsl:template> 

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

    <xsl:template match="Child"> 
     <newChild> 
      <xsl:attribute name="chars"> 
       <xsl:apply-templates mode="asEscapedString" select="." /> 
      </xsl:attribute> 
     </newChild> 

    </xsl:template> 
    <xsl:template match="*"> 
     <xsl:apply-templates select="Child"/> 
    </xsl:template> 
</xsl:stylesheet> 

這將產生以下輸出:

<newChild chars="&lt;Child attr=&amp;quot;thing&amp;quot;&gt;stuff&lt;/Child&gt;"/> 

注意:此遠離的一般的解決方案。這適用於你的簡單例子。