显示来自不同块的相应XML节点

时间:2013-04-08 18:57:25

标签: xml xslt

假设我有以下XML块..

<items>
    <books>
        <book>
            <name>a</name>
            <author>b</author>
        </book>
        <book>
            <name>d</name>
            <author>e</author>
        </book>
    </books>

    <infos>
        <info>
            <id>1</id>
            <year>c</year>
        </info>
        <info>
            <id>2</id>
            <year>f</year>
        </info>
    </infos>
</items>

其中'info'的每个实例对应于'book'的实例。如果items / infos / info / id指的是书元素的位置 我正在尝试输出以下内容......

a  
b  
c  

d
e
f

提前致谢...任何帮助都会受到关注!

1 个答案:

答案 0 :(得分:0)

如果第n个info元素与第n个book匹配,那么您可以谨慎使用position()函数。例如

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="text" />

  <xsl:template match="/">
    <xsl:apply-templates select="items/books/book" />
  </xsl:template>

  <xsl:template match="book">
    <xsl:variable name="bookNum" select="position()" />
    <xsl:variable name="info" select="/items/infos/info[$bookNum]" />
    <xsl:value-of select="name" />
    <xsl:text>&#x0A;</xsl:text>
    <xsl:value-of select="author" />
    <xsl:text>&#x0A;</xsl:text>
    <xsl:value-of select="$info/year" />
    <xsl:text>&#x0A;</xsl:text>
    <xsl:text>&#x0A;</xsl:text>
  </xsl:template>
</xsl:stylesheet>

虽然对于比这个简单示例更复杂的事情,我可能会为info元素定义一个单独的模板,并在<xsl:apply-templates select="/items/infos/info[$bookNum]" />模板中放置book,而不是全部放入内联。

相关问题