2013-05-03 92 views
0

我試圖構建一個XSLT文件,查找類似下面,它使用的標籤無效的嵌套的XML文件:如果我想如何解析「無效的」嵌套的XML標記

<Page> 
<Content> 
    <par>This content <i>contains</i> some HTML <b><i>tags</i></b>.</par> 
    <par>This content <b>also</b> contains some HTML <i><b>tags</b></i>.</par> 
</Content> 
</Page> 

我們輸出內容到一個新的文檔,我有這樣的事情:

<xsl:template match="Page/Content"> 
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text> 
    <xsl:for-each select="par"> 
    <xsl:apply-templates select="."/> 
    </xsl:for-each> 
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> 
</xsl:template> 

<xsl:template match="par"> 
    <p><xsl:value-of select="." /></p> 
</xsl:template> 

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

<xsl:template match="i"> 
    <em><xsl:value-of select="." /></em> 
</xsl:template> 

我的問題是我怎麼需要編輯template match="par"使得<b><i>標籤正確顯示?

我試過的東西

<xsl:template match="par"> 
    <p> 
    <xsl:apply-templates select="i"/> 
    <xsl:apply-templates select="b"/> 
    <xsl:value-of select="." /></p> 
</xsl:template> 

但始終會導致輸出的順序不正確,因爲<i><b>標籤完整的段落之前顯示。 有沒有可能在不改變原始XML格式的情況下做到這一點?

回答

1

我沒有在您的示例輸入中看到任何不正確的嵌套標籤,所以我不確定你的意思。 XSLT無法處理錯誤的嵌套XML,因爲它不是有效的XML。

無論如何,你的XSLT的主要問題是,你正在使用value-of,你應該使用apply-templates

<xsl:template match="Page/Content"> 
    <xsl:text disable-output-escaping="yes">&lt;![CDATA[</xsl:text> 
    <xsl:apply-templates select="par"/> 
    <xsl:text disable-output-escaping="yes">]]&gt;</xsl:text> 
</xsl:template> 

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

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

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

但是,你還沒有告訴我們你想要所以我輸出不確定這會完全解決您的問題。

+0

感謝您的快速答案。這似乎解決了我的問題。的確,我錯誤地認爲XML是無效的,這似乎是不真實的。 – Honoki 2013-05-03 10:39:04