XSLT 1.0将分隔的字符串转换为节点集

时间:2012-01-31 06:37:08

标签: xml xslt xpath xslt-1.0

我有一个变量$ colors是一个字符串

<xsl:variable name="colors" select="'red,green,blue,'" />

我需要一个新的变量$ colorElements,它是一个节点集

<color>red</color>
<color>green</color>
<color>blue</color>

(是吗?节点集可以没有root吗?)

永远不会直接输出

$colorElements。我只需要它,实际上是一个列表变量。

XSLT 1.0,没有node-set()以外的扩展名。

2 个答案:

答案 0 :(得分:3)

使用:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
  <xsl:output method="xml" indent="yes"/>

  <xsl:variable name="colors" select="'red,green,blue,'" />

  <xsl:template match="/">

    <xsl:variable name="colorElements">
      <xsl:call-template name="split">
        <xsl:with-param name="pText" select="$colors"/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:for-each select="msxsl:node-set($colorElements)">
      <xsl:copy-of select="color"/>
    </xsl:for-each>

  </xsl:template>

  <xsl:template name="split">
    <xsl:param name="pText"/>

    <xsl:variable name="separator">,</xsl:variable>

    <xsl:choose>
      <xsl:when test="string-length($pText) = 0"/>
      <xsl:when test="contains($pText, $separator)">
        <color>
          <xsl:value-of select="substring-before($pText, $separator)"/>
        </color>
        <xsl:call-template name="split">
          <xsl:with-param name="pText" select="substring-after($pText, $separator)"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <color>
          <xsl:value-of select="$pText"/>
        </color>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

</xsl:stylesheet>

答案 1 :(得分:0)

这个怎么样?:

<?xml version="1.0"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xs="http://www.w3.org/2001/XMLSchema" 
                exclude-result-prefixes="xs">
 <xsl:output method="xml" indent="yes" encoding="utf-8" />
 <xsl:variable name="colors" select="'red,green,blue,'" />
 <xsl:template match="/" name="main">
  <csv-to-xml>
   <xsl:for-each select="tokenize($colors, ',')[position()!=last()]">
   <!-- The predicate is needed because of the extraneous comma
        at the end of the red,green,blue, list. -->
    <color><xsl:value-of select="." /></color>
   </xsl:for-each>
  </csv-to-xml>
 </xsl:template>
</xsl:stylesheet>