6

我想动态创建具有动态名称的变量,以便以后在我的转换中使用,但要做到这一点,我需要动态生成 XSL,然后在同一个脚本中运行它。

这只是我正在寻找的一个粗略的伪代码示例。

      <xsl:for-each select="//constants/constant" >
        <xsl:variable >
            <xsl:attribute name="name">
              <xsl:value-of select="@name"/>
            </xsl:attribute>
          <xsl:attribute name="select">
            <xsl:value-of select="@value"/>
          </xsl:attribute>
        </xsl:variable>
      </xsl:for-each>

我可以使用 XSL 动态构建 XSL 以便稍后在同一脚本中运行吗?

注意:我们的 XML 是通过运行 CL XSL 转换引擎的批处理来转换的;因此,仅在 XSL 文档中引用 XSL 样式表不是一种选择。

4

2 回答 2

15

XSLT 有一个特殊的内置特性,它支持生成输出,这就是 XSLT本身。

这是<xsl:namespace-alias>XSLT 指令。

正如 XSLT 1.0 Spec所解释的那样:

"

<!-- 分类:顶级元素 -->
<xsl:命名空间别名
  样式表前缀 = 前缀 | “#默认”
  结果前缀 = 前缀 | "#default" />

样式表可以使用该xsl:namespace-alias元素来声明一个命名空间 URI 是另一个命名空间 URI 的别名。当一个文本命名空间 URI 被声明为另一个命名空间 URI 的别名时,结果树中的命名空间 URI 将是文本命名空间 URI 作为别名的命名空间 URI,而不是文本命名空间 URI 本身。该xsl:namespace-alias元素声明绑定到属性指定前缀stylesheet-prefix的命名空间URI 是绑定到属性指定前缀的命名空间URI 的别名result-prefix。因此,该stylesheet-prefix属性指定将出现在样式表中的命名空间 URI,而该result-prefix属性指定将出现在结果树中的相应命名空间 URI。"

下面是一个生成xsl:stylesheet包含 an的转换的小示例xsl:variable它以所需的方式构造:

<xsl:stylesheet 版本="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xxx="my:dummyNS" 排除结果前缀="xxx"
 >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:namespace-alias result-prefix="xsl" stylesheet-prefix="xxx"/>

 <xsl:template match="/*">
  <xxx:stylesheet 版本="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xxx:变量名="{@name}">
    <xsl:value-of select="."/>
  </xxx:变量>
 </xxx:样式表>
 </xsl:模板>
</xsl:stylesheet>

When this transformation is applied on the following XML document:

    <v name="myVarName">myValue</v>

the wanted result is produced:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:variable name="myVarName">myValue</xsl:variable>
</xsl:stylesheet>

Then the next step will be to launch in your "script" this dynamically generated XSLT transformation.

于 2008-12-11T00:56:17.313 回答
1

What you want is not possible at present in pure XSLT (1.0 or 2.0).

If you are useing the Saxon 9.x XSLT processor, there is a couple of extension functions that implement this: saxon:compile-stylesheet() and saxon:transform().

一个问题的解决方案真的需要这样的功能是非常罕见的,如果你描述了这个问题,人们很可能会找到解决它的最佳方法,而不必动态地生成和执行 XSLT 样式表。

于 2008-12-11T14:22:25.843 回答