使用XSLT确定节点的位置

时间:2013-09-30 01:42:35

标签: xslt xslt-1.0

给出以下XML:

<data>
    <content>
        <section link-id="32">
            <entry id="9">
                <title handle="apples">Apples</title>
            </entry>
            <entry id="1">
                <title handle="oranges">Oranges</title>
            </entry>            
            <entry id="4">
                <title handle="pears">Pears</title>
            </entry>
        </section>
        <section link-id="23">
            <entry id="59">
                <title handle="chevrolet">Chevrolet</title>
            </entry>
            <entry id="31">
                <title handle="toyota">Toyota</title>
            </entry>            
            <entry id="54">
                <title handle="bmw">BMW</title>
            </entry>
        </section>
    </content>
</data>

由此XSL设计:

<xsl:template match="data">
<html>
<body>

<xsl:apply-templates select="content/section" />      

</body>
</html>

</xsl:template>

<xsl:template match="content/section">
    <ul>
        <li>
            Title: <xsl:value-of select="entry/title"/>
        </li>   
        <li>
            Position: <xsl:value-of select="position()"/>
        </li>               
    </ul>
</xsl:template>

我如何显示和表示所选entry节点的顺序(1-6)的整数?预期值将为1和4.该示例显示值1和2,即所选节点集中的位置。我想要的是XML文件中的数字位置,而不是选择。

2 个答案:

答案 0 :(得分:0)

我不清楚你在问什么,作为你的&#34; 1和4&#34;并参考前一节点集中的&#34;位置&#34;有点混乱。但我认为你有几个选择。

您可以从头开始处理所有条目:

<body>
  <ul>
    <xsl:apply-templates select="content/section/entry"/>
  </ul>
</body>
...
<xsl:template match="entry">
  <li>
    Title: <xsl:apply-templates select="title"/>
  </li>
  <li>
    Position: <xsl:apply-templates select="position()"/>
  </li>
</xsl:template>

或者,如果您发现必须单独处理这些部分和条目,那么您将发现自己处于position()没有帮助的条目中。此时,您可以使用<xsl:number level="any"/>。如果您位于条目深处,则可以使用<xsl:number count="entry" level="any"/>

答案 1 :(得分:0)

你正在混淆“position”(一个描述你想要的英文单词)和“position()”(XPath函数给你一些完全不同的东西)。

尝试

<xsl:for-each select="entry[1]">
  <xsl:number level="any" from="content"/>
</xsl:for-each>

看起来好像是故意使用XSLT 1.0“功能”,其中应用于节点集的xsl:value-of忽略除第一个节点之外的所有节点。如果您希望您的代码与2.0兼容(并且读者可以理解),最好通过编写select="entry[1]/title"来明确这一点。

相关问题