我有以下 xml 文件:
<courses>
<course>
<name>Course 1</name>
<code>00162</code>
<questions>2,2,1,1,2,1,1,1</questions>
</course>
</courses>
我需要查询文件(我使用 xpath)来分割“问题”元素,检查每个数字出现的位置并检查它是数字 1 还是数字 2。
基本上我需要在 xpath 中这样做:
Dim ints As String() = QuestionsString.ToString.Split(",")
Dim i As Integer
For i = 0 To UBound(ints)
If ints(i) = "2" Then
'do something
Else
'do something else
End If
Next
根据评论更新
嗨,谢谢你。我本来打算编辑
问题,因为它不正确。我想
例如,获取所有课程名称
以及其“questions”元素的代码
(分割后)第二个有“2”
位置,如 1 所示,2,2,1,1,1,2,1
谢谢!
在 XSLT 1.0 中,您将使用递归模板来拆分字符串。
借用自@Tomalak 对类似问题的回答 https://stackoverflow.com/questions/2850100/comma-separated-string-parsing-xslt/2850181#2850181,是一个例子:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<!--Call the recursive template to split the string-->
<xsl:call-template name="split">
<xsl:with-param name="list" select="/courses/course/questions" />
</xsl:call-template>
</xsl:template>
<xsl:template name="split">
<xsl:param name="list" select="''" />
<xsl:param name="separator" select="','" />
<xsl:if test="not($list = '' or $separator = '')">
<xsl:variable name="head" select="substring-before(concat($list, $separator), $separator)" />
<xsl:variable name="tail" select="substring-after($list, $separator)" />
<!--Use the parsed value to do something-->
<xsl:call-template name="handleQuestion">
<xsl:with-param name="value" select="$head"/>
</xsl:call-template>
<xsl:call-template name="split">
<xsl:with-param name="list" select="$tail" />
<xsl:with-param name="separator" select="$separator" />
</xsl:call-template>
</xsl:if>
</xsl:template>
<xsl:template name="handleQuestion">
<xsl:param name="value" />
<xsl:choose>
<xsl:when test="$value=2">
<!--Do something-->
</xsl:when>
<xsl:otherwise>
<!--Do something else-->
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
在 XSLT 2.0 中,您可以使用tokenize()功能 http://www.xsltfunctions.com/xsl/fn_tokenize.html:
<?xml version="1.0"?>
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fn="http://www.w3.org/2005/xpath-functions"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:template match="/">
<xsl:for-each select="tokenize(/courses/course/questions,',')">
<xsl:choose>
<xsl:when test="number(.)=2">
<!--Do something-->
</xsl:when>
<xsl:otherwise>
<!--Do something else-->
</xsl:otherwise>
</xsl:choose>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)