在XSL中循环遍历XML元素

时间:2011-07-31 20:01:15

标签: xml loops xslt

我有像这样的XML文件

<ViewFields> 
<FieldRef Name="Approval Status" /> 
<FieldRef Name="Requirement Status" /> 
<FieldRef Name="Development Status" /> 
<FieldRef Name="Testing Status" />
</ViewStatus>

我有以下XSL代码来获取FieldRef值。

<xsl:template name="FieldRef_body.Status" match="FieldRef[@Name='ViewFields/FieldRef[1]/@Name']" mode="body">
        <xsl:param name="thisNode" select="."/>
            <xsl:choose>
                <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'Completed'">
                    <img src="/_layouts/images/IMNON.png" alt="Status: {$thisNode/@Status}"/>
                </xsl:when>
                <xsl:when test="$thisNode/@*[name()=current()/@Name] = 'In Progress'">
                    <img src="/_layouts/images/IMNIDLE.png" alt="Status: {$thisNode/@Status}"/>
                </xsl:when>
                <xsl:otherwise>
                    <img src="/_layouts/images/IMNBUSY.png" alt="Status: {$thisNode/@Status}"/>
                </xsl:otherwise>
            </xsl:choose>
    </xsl:template>

我试图通过FieldRef * [x] *来循环获取值,它不会返回任何内容。我想通过循环将FieldRef值赋给@Name变量。

2 个答案:

答案 0 :(得分:1)

这很明显

  1. match="FieldRef[@Name='ViewFields/FieldRef[1]/@Name']"。 No Name属性的字符串值为字符串'ViewFields/FieldRef[1]/@Name'。你最有可能想要一个XPath表达式,而不是字符串。使用match="FieldRef[@Name=ViewFields/FieldRef[1]/@Name]"

  2. 提供的XML文档中没有Name属性,字符串值为"Completed"或字符串值为"In Progress"

  3. 此外,XML文档中根本没有Status属性。

答案 1 :(得分:1)

您的问题没有正确回答所需的所有上下文,但您应该考虑将构造简化为“for-each”以进行循环。

给出xml

<ViewFields> 
<FieldRef Name="Approval Status" />
<FieldRef Name="Requirement Status" /> 
<FieldRef Name="Development Status" /> 
<FieldRef Name="Testing Status" />
</ViewFields>

使用xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template name="main" match="/">
    <xsl:for-each select="/ViewFields/FieldRef">
        <xsl:choose>
            <xsl:when test="@Name = 'Approval Status'">
                <ApprovalStatus/>
            </xsl:when>
            <xsl:when test="@Name = 'Requirement Status'">
                <RequirementStatus/>
            </xsl:when>
            <xsl:otherwise>
                <SomethingElse/>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:for-each>
</xsl:template>

这可能更接近你想要的东西。

相关问题