2012-09-12 49 views
2

給定一個輸入XML文檔這樣的:轉換 '嵌入式' XML文檔到XSLT CDATA輸出(1.0)

<?xml version="1.0" encoding="utf-8"?> 
<title> This contains an 'embedded' HTML document </title> 
<document> 
<html> 
<head><title>HTML DOC</title></head> 
<body> 
Hello World 
</body> 
</html> 
</document> 
</root> 

如何可以提取 '內' HTML文件;將其呈現爲CDATA幷包含在我的輸出文檔中?

所以輸出文檔將是一個HTML文檔;其中包含一個文本框顯示元素爲文本(所以它將顯示內部文檔的'源視圖')。

我已經試過這樣:

<xsl:template match="document"> 
<xsl:value-of select="*"/> 
</xsl:template> 

但這僅呈現文本節點。

我已經試過這樣:

<xsl:template match="document"> 
<![CDATA[ 
<xsl:value-of select="*"/> 
]]> 
</xsl:template> 

但這逃脫實際XSLT和獲取:

&lt;xsl:value-of select="*"/&gt; 

我已經試過這樣:

<xsl:output method="xml" indent="yes" cdata-section-elements="document"/> 
[...] 
<xsl:template match="document"> 
<document> 
<xsl:value-of select="*"/> 
</document> 
</xsl:template> 

這並插入一個CDATA部分,但輸出仍包含文本(剝離元素):

<?xml version="1.0" encoding="UTF-8"?> 
<html> 
    <head> 
     <title>My doc</title> 
    </head> 
    <body> 
     <h1>Title: This contains an 'embedded' HTML document </h1> 
     <document><![CDATA[ 
               HTML DOC 

                   Hello World 

           ]]></document> 
    </body> 
</html> 
+0

你能告訴你的預期輸出嗎? –

回答

11

你需要清理兩處困惑。

首先,您可能想要xsl:copy-of而不是xsl:value-of。後者返回元素的字符串值,前者返回該元素的副本。

其次,xsl:outputcdata-section-elements屬性會影響文本節點的序列化,但不是元素和屬性。一種方式得到你想要將自己的序列化的HTML是什麼,沿以下(未測試)行:

<xsl:template match="document/descendant::*"> 
    <xsl:value-of select="concat('&lt;', name())"/> 
    <!--* attributes are left as an exercise for the reader ... *--> 
    <xsl:text>&gt;</xsl:text> 
    <xsl:apply-templates/> 
    <xsl:value-of select="concat('&lt;/', name(), '>')"/> 
</xsl:template> 

但是更快的方法是像下面這樣的解決方案(嬌氣的讀者,停止閱讀現在),由我的朋友托米·烏斯丁向我指出。從xsl:output刪除該cdata-section-elements屬性並更換模板與document元素:

<xsl:template match="document"> 
    <document> 
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text> 
    <xsl:copy-of select="./html"/> 
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> 
    </document> 
</xsl:template> 
+0

不錯 - 我開始意識到我需要在這裏編碼< > - 但之前沒有看到disable-output-escaping選項。事實上,我已經使用不同的字符(法語引號!)來表示尖括號!感謝您的額外提示:值的/複製以及。歡呼 – monojohnny

+0

謝謝你。絕對不適合那些嬌氣的讀者。或者我應該說,那些成爲優雅。 hhhheee –

+0

由於某些原因,撒克遜9堅持逃避'<![CDATA'無論如何。至少這是它在我的XSLT中的作用:https://github.com/gioele/rng-doc/blob/600d09759bf1158e132b89c0e6adaad7c5be0bb2/rng-doc.xsl#L131 – gioele