【问题标题】:How to iterate over IDREFS values in XSLT 1.0?如何在 XSLT 1.0 中迭代 IDREFS 值?
【发布时间】:2021-08-16 17:06:39
【问题描述】:

我有一个使用 IDREFS 字段的 xml。我需要提取这些 id 以将它们放入自己的元素中。

这是我认为我需要的基本结构,但我不知道在选择函数中使用什么。

<xsl:template match="node_With_IDREFS_field">
   <xsl:for-each select="EACH ID IN @idrefsField">
      <xsl:element name="newElement">
        <xsl:attribute name="ref"><xsl:value-of select="THE IDREF"/></xsl:attribute>
      </xsl:element>
   </xsl:for-each>
   <!-- keep rest of content -->
   <xsl:apply-templates select="@*|node()"/>
</xsl:template>

所以来自这个节点

&lt;node_With_IDREFS_field idrefsField="id1 id2"/&gt;

结果是

<node_With_IDREFS_field>
  <newElement ref="id1"/>
  <newElement ref="id2"/>
</node_With_IDREFS_field>

感谢您的帮助。

【问题讨论】:

  • 请向我们展示您的输入示例。
  • 刚刚做到了!可能是在您输入评论时写的!

标签: xml xslt xslt-1.0


【解决方案1】:

您需要标记idrefsField 属性的值。 XSLT 1.0 没有原生 tokenize() 函数,因此您需要调用递归命名模板来为您执行此操作:

<xsl:template match="node_With_IDREFS_field">
    <xsl:copy>
        <xsl:call-template name="tokenize">
            <xsl:with-param name="text" select="@idrefsField"/>
        </xsl:call-template>
    </xsl:copy>
</xsl:template>

<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="' '"/>
    <xsl:variable name="token" select="substring-before(concat($text, $delimiter), $delimiter)" />
        <xsl:if test="$token">
            <newElement ref="{$token}"/>
        </xsl:if>
        <xsl:if test="contains($text, $delimiter)">
            <!-- recursive call -->
            <xsl:call-template name="tokenize">
                <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
            </xsl:call-template>
        </xsl:if>
</xsl:template>

或者,如果您的处理器支持,您可以使用 EXSLT str:tokenize() 扩展函数。

【讨论】:

  • 如果我想将 newElement 的实际名称作为参数传递,我该怎么做?我在模板中添加了 , 参数声明,然后添加了 但它没有不行。
  • 您需要使用xsl:element instruction 来创建具有计算名称的元素,例如&lt;xsl:element name="$elementName"/&gt;.
  • 我确实尝试过,但结果是一个空节点&lt;xsl:element name="$elementName"&gt;&lt;xsl:attribute name="ref"&gt;&lt;xsl:value-of select="$token"/&gt;&lt;/xsl:attribute&gt;&lt;/xsl:element&gt; 我得到&lt;node_With_IDREFS_field/&gt;
  • 哦,我错过了 $elementName 的 {}!
【解决方案2】:

你可以试试这个:

<xsl:template match="node_With_IDREFS_field">
    <xsl:element name="node_With_IDREFS_field">
        <xsl:for-each select="tokenize(@idrefsField,' ')">
            <xsl:element name="newElement">
                <xsl:attribute name="ref">
                    <xsl:value-of select="."/>
                </xsl:attribute>
            </xsl:element>
        </xsl:for-each>
    </xsl:element>
</xsl:template>

【讨论】:

  • 这个问题是关于 XSLT 1.0 的。您的答案需要 XSLT 2.0 或更高版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 2022-10-04
  • 2014-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多