我对 xslt 比较陌生,我需要使用当前帖子的 pid 根据哪个帖子选择评论元素
我遇到问题的 XSLT 部分
<xsl:for-each select="posts/post">
<div class="post">
<h3><xsl:value-of select="ptitle"/></h3>
<span><xsl:value-of select="ptext"/></span>
<xsl:variable name="pid" select="@pid" />
<!-- Here i need to select the comment according to the pid -->
</div>
<br />
</xsl:for-each>
XML 代码
<posts>
<post pid="p2">
<ptitle>APPLICATIONS OF THE FUTURE</ptitle>
<pfeatureimage>aig.jpg</pfeatureimage>
<ptext xml:lang="en">just text </ptext>
<pdate>25062013</pdate>
<pimg>future.jpg</pimg>
<pimg>future.jpg</pimg>
<pimg>future.jpg</pimg>
<pauthorid>a3</pauthorid>
</post>
</posts>
<comments>
<comment cid="c1">
<pid>p2</pid>
<uid>u2</uid>
<ctext>other t</ctext>
<likes>5</likes>
<dislikes>1</dislikes>
</comment>
<comment cid="c2">
<pid>p3</pid>
<uid>u2</uid>
<ctext>bogsg</ctext>
<likes>5</likes>
<dislikes>1</dislikes>
</comment>
</comments>
最佳答案
解决 XSLT 中此类交叉引用问题的方法是使用 key 。您将关键定义放在样式表的顶层(任何模板之外):
<xsl:key name="commentsByPid" match="comment" use="pid" />
match
表达式确定要查看哪些节点,use
是相对于每个匹配节点进行评估的路径,以确定键值(因此在此在这种情况下,它将采用每个匹配的 comment
内的 pid
元素的字符串值。
通过此键定义,您可以使用 key
函数高效查找与当前帖子的 pid
属性匹配的所有评论:
<xsl:for-each select="posts/post">
<div class="post">
<h3><xsl:value-of select="ptitle"/></h3>
<span><xsl:value-of select="ptext"/></span>
<xsl:for-each select="key('commentsByPid', @pid)">
<!-- do whatever you need with the <comment> here -->
</xsl:for-each>
</div>
<br />
</xsl:for-each>
关于xml - XSLT 嵌套选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21242943/