如何在<xsl:attribute> text?</xsl:attribute>中生成标记

时间:2015-02-08 19:54:52

标签: xslt

我的XSLT样式表生成Bootstrap HTML,其中一些元素可能包含data-...个属性,以将其他数据传递给框架。例如,我有这个代码来生成popover元素:

<xsl:template match="foo">
  <a href="#" data-toggle="popover" data-placement="top" data-trigger="hover" data-html="true">
    <xsl:attribute name="title">Popover Title</xsl:attribute>
    <xsl:attribute name="data-content">This is some additional content.</xsl:attribute>
    <xsl:text>Link</xsl:text>
  </a>
</xsl:template>

data-content属性应包含其他标记。结果输出应该类似于

<a href="#" ... data-content="This is <em>some</em> additional <a href='#'>content</a>.">Link</a>

在这种情况下,如何为<xsl:attribute>生成标记文本?

(有点相关:herehere以及here。)

答案

感谢您的回答!虽然我认为kjhughes's answer提供了技术上正确的解决方案来正确实施我需要的内容,但我认为Ian's answer更直接地解决了我的问题。

3 个答案:

答案 0 :(得分:1)

你不能将非转义标记放在属性值中,但是you don't need to - 如果你将尖括号(以及引号中的任何&符号和引号)转义为实体引用引导程序仍将呈现html正确地在popover中。

<a href="#" data-content="This is &lt;em&gt;some&lt;/em&gt; additional &lt;a href='#'&gt;content&lt;/a&gt;.">Link</a>

在XSLT中实现这一目标的最简单方法是使用CDATA部分:

<xsl:attribute name="data-content"
  ><![CDATA[This is <em>some</em> additional content
    &amp; a <a href="#">link</a>.]]></xsl:attribute>

如果需要,序列化程序会为你转义它。

答案 1 :(得分:0)

您无法在xsl:attribute内生成标记,因为XML不允许在属性内部使用非转义标记。

具体而言,AttValue <完全禁止&&,除非Reference是正确形成AttValue ::= '"' ([^<&"] | Reference)* '"' | "'" ([^<&'] | Reference)* "'" 的一部分:< / p>

Reference      ::=      EntityRef | CharRef
EntityRef      ::=      '&' Name ';'
CharRef        ::=      '&#' [0-9]+ ';'
                      | '&#x' [0-9a-fA-F]+ ';'

支持定义:

{{1}}

HTML,即使是grammar rule,也不允许在属性值中使用非转义标记。

在属性值中添加转义标记是可行的但很难看。特别是对于标记较多的内容,我建议单独创建内容,然后通过JavaScript以程序方式关联它,而不是通过属性值以声明方式关联。有很多这样做的例子,包括你的一篇参考文献中提到的HTML5

答案 2 :(得分:0)

不是&#34;官方&#34;这样做的方法,但在使用lxml处理XML和XSLT样式表时,请考虑在样式表中使用XSLT extension elements。这些自定义元素允许您在处理期间元素匹配时运行Python代码,并且该代码可以修改/编辑输出文档的某些部分。