如何在 XSLT 的 HTML 输出中发出节点的转义 XML 表示 [英] How do I Emit Escaped XML representation of a Node in my XSLT's HTML Output
问题描述
我正在将 XML 转换为 HTML 文档.在本文档中,我想为刚刚转换的节点嵌入 XML 标记(HTML 文档是技术规范).
I'm transforming XML to an HTML document. In this document I want to embed XML markup for a node that was just transformed (the HTML document is a technical spec).
例如,如果我的 XML 是这样的:
For example, if my XML was this:
<transform-me>
<node id="1">
<stuff type="floatsam">
<details>Various bits</details>
</stuff>
</node>
</transform-me>
我希望我的 XSLT 输出看起来像这样:
I'd want my XSLT output to look something like this:
<h1>Node 1</h1>
<h2>Stuff (floatsam)</h2>
Various bits
<h2>The XML</h2>
<stuff type="floatsam">
<details>Various bits</details>
</stuff>
我希望有一个 XSLT 函数可以在我的 <stuff> 中调用.模板,我可以将当前节点 (.) 传递给该模板,并为 <stuff> 取回转义的 XML 标记.以及它的所有后代.我有一种感觉 unparsed-text() 可能是要走的路,但无法让它工作.
I'm hoping there is an XSLT function that I can call in my <stuff> template to which I can pass the current node (.) and get back escaped XML markup for <stuff> and all its descendants. I have a feeling unparsed-text() might be the way to go but can't get it to work.
推荐答案
非常简单的模板
<xsl:template match="node()" mode="print">
<xsl:choose>
<!-- is it element? -->
<xsl:when test="name()">
<!-- start tag -->
<xsl:text><</xsl:text>
<xsl:value-of select="name()" />
<!-- attributes -->
<xsl:apply-templates select="@*" mode="print" />
<xsl:choose>
<!-- has children -->
<xsl:when test="node()">
<!-- closing bracket -->
<xsl:text>></xsl:text>
<!-- children -->
<xsl:apply-templates mode="print" />
<!-- end tag -->
<xsl:text></</xsl:text>
<xsl:value-of select="name()" />
<xsl:text>></xsl:text>
</xsl:when>
<!-- is empty -->
<xsl:otherwise>
<!-- closing bracket -->
<xsl:text>/></xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<!-- text -->
<xsl:otherwise>
<xsl:copy />
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="@*" mode="print">
<xsl:text> </xsl:text>
<xsl:value-of select="name()" />
<xsl:text>="</xsl:text>
<xsl:value-of select="." />
<xsl:text>"</xsl:text>
</xsl:template>
使用过
<xsl:apply-templates mode="print" />
如果需要,您甚至可以添加漂亮的印刷品.
You can even add pretty printing if you want.
这篇关于如何在 XSLT 的 HTML 输出中发出节点的转义 XML 表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!