Gan*_*ori 1 xml xslt tokenize xslt-2.0
我刚刚开始研究 XSLT。我的输入和预期输出如下,XSLT 也在下面给出。我现在面临两个问题
net.sf.saxon.trans.XPathException: Required item type of the context item for the attribute axis is node(); supplied value has item type xs:string<students>
<field name="id">1,2,3</field>
<field name="name">a,b,c</field>
</students>
Run Code Online (Sandbox Code Playgroud)
<students>
<student>
<id>1</id>
<name>a</name>
</student>
<student>
<id>2</id>
<name>b</name>
</student>
<student>
<id>3</id>
<name>c</name>
</student>
</students>
Run Code Online (Sandbox Code Playgroud)
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/" name="main">
<xsl:for-each select="students/field">
<xsl:for-each select="tokenize(.,',')">
<xsl:element name="{@name}">
<xsl:value-of select="."/>
</xsl:element>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
我不确定为什么您展示的样式表使用 XSLT 1.0,因为您用 XSLT 2.0 标记了问题,而 tokenize 是一个 2.0 函数。
此外,您的预期输出包含我认为的错字。也许这就是你想写的:
<student>
<id>1</id>
<name>a</name>
</student>
<student>
<id>2</id>
<name>b</name>
</student>
Run Code Online (Sandbox Code Playgroud)
为什么会出现异常
在 XSLT 中,表达式严重依赖于上下文。像下面这样的一行:
<xsl:element name="{@name}">
Run Code Online (Sandbox Code Playgroud)
取决于上下文,因为它检索name当前模板匹配项的属性值或xsl:for-each.
在你的情况下,上下文是这样的:
<xsl:for-each select="tokenize(.,',')">
Run Code Online (Sandbox Code Playgroud)
所以,上下文 for{@name}是一个标记化的字符串——当然没有任何属性。
样式表
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output indent="yes" method="xml"/>
<xsl:strip-space elements="*"/>
<xsl:template match="/students">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="field[@name='id']">
<xsl:variable name="match" select="."/>
<xsl:for-each select="tokenize(.,',')">
<xsl:variable name="id-pos" select="position()"/>
<student>
<id>
<xsl:value-of select="."/>
</id>
<name>
<xsl:value-of select="tokenize($match/following-sibling::field[@name='name'],',')[position() = $id-pos]"/>
</name>
</student>
</xsl:for-each>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
Run Code Online (Sandbox Code Playgroud)
输出
<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<id>1</id>
<name>a</name>
</student>
<student>
<id>2</id>
<name>b</name>
</student>
<student>
<id>3</id>
<name>c</name>
</student>
</students>
Run Code Online (Sandbox Code Playgroud)