迭代以空格分隔的列表的元素

时间:2013-07-30 01:31:48

标签: xslt xpath xslt-1.0

我试图找出哪种方法是使用XSL迭代空格分隔列表的元素的最简单方法。假设我们有以下XML数据文件:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <!-- this list has 6 items -->
    <list>this is a list of strings</list>
</data>

list 元素可以在XML Schema中定义,如下所示:

<xs:element name="list" type="strlist" />

<xs:simpleType name="strlist">
    <xs:list itemType="xs:string" />
</xs:simpleType>

我不确定XSL规范是否直接支持这种构造,但我认为它应该可以在XML Schema中使用。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

XML Schema早于XSLT 2.0,因此XSLT 2.0可以使用tokenize()来容纳它。

XSLT 1.0早于XML Schema,因此您需要一个用于填充字符串的递归模板调用:

T:\ftemp>type tokenize.xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
    <!-- this list has 6 items -->
    <list>this is a list of strings</list>
</data>
T:\ftemp>xslt tokenize.xml tokenize.xsl
this,is,a,list,of,strings
T:\ftemp>type tokenize.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="1.0">

<xsl:output method="text"/>

<xsl:template match="data">
  <xsl:call-template name="tokenize">
    <xsl:with-param name="string" select="normalize-space(list)"/>
  </xsl:call-template>
</xsl:template>

<xsl:template name="tokenize">
  <xsl:param name="string"/>
  <xsl:choose>
    <xsl:when test="contains($string,' ')">
      <xsl:value-of select="substring-before($string,' ')"/>
      <xsl:text>,</xsl:text>
      <xsl:call-template name="tokenize">
        <xsl:with-param name="string" select="substring-after($string,' ')"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$string"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

</xsl:stylesheet>
T:\ftemp>xslt2 tokenize.xml tokenize2.xsl
this,is,a,list,of,strings
T:\ftemp>type tokenize2.xsl
<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                version="2.0">

<xsl:output method="text"/>

<xsl:template match="data">
  <xsl:value-of select="tokenize(list,'\s+')" separator=","/>
</xsl:template>

</xsl:stylesheet>
T:\ftemp>

答案 1 :(得分:1)

XSLT 2.0直接支持这一点:在模式感知转换中,您可以编写

<xsl:for-each select="data(list)">
  ...
</xsl:for-each>

如果在带有列表类型的模式中定义元素“list”,则会遍历标记。

但你也可以通过编写

来没有架构
<xsl:for-each select="tokenize(list, '\s+')">...</xsl:for-each>

在XSLT 1.0中,您需要使用递归命名模板;你可以在www.exslt.org找到一个现成的str:tokenize模板复制到你的样式表中。