xml - XSLT 嵌套选择

标签 xml xslt xpath

我对 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/

相关文章:

javascript - HTML5 : how to load an image onClick in a specific place

c# - 如何从 Xelement 中获取根元素

c# - 将 XSLT 应用于内存中的 XML 并返回内存中的 XML

xml - 为什么 XPath 不适用于 xmlns 属性

XPath 只选择一定数量的级别

c# - 如何在 C# 中设置命名空间 URI?

java - 从 xml 中获取数据使用 Xquery with starts with 函数

javascript - 当字符串包含单引号时使用js替换XSL变量的值

xml - XSL : How to change attribute X when attribute Y is 'A' , B' 或 'F'?

shell - 如何使用 scrapy response.xpath 提取 HTML 属性的值?