显示来自不同块的相应XML节点
假设我有以下XML块显示来自不同块的相应XML节点,xml,xslt,Xml,Xslt,假设我有以下XML块 <items> <books> <book> <name>a</name> <author>b</author> </book> <book> <name>d</name> <author
<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>
先谢谢你。。。任何帮助都将受到感谢 如果第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>
</xsl:text>
<xsl:value-of select="author" />
<xsl:text>
</xsl:text>
<xsl:value-of select="$info/year" />
<xsl:text>
</xsl:text>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
;
;
;
;
尽管对于比这个简单示例更复杂的内容,我可能会为
info
元素定义一个单独的模板,并将
放在书的模板中,而不是将其全部内联。感谢您的输入。。如果我想使用foreach怎么办?@user1748076我会告诉您使用应用模板
,-)认真地说,对于每一本select=“items/books/book”
,您可以在中使用完全相同的position()
技巧,第一本书将得到相同的1,第二本书将得到相同的2,以此类推。
<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>
</xsl:text>
<xsl:value-of select="author" />
<xsl:text>
</xsl:text>
<xsl:value-of select="$info/year" />
<xsl:text>
</xsl:text>
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>