xpath:如何 select 项目 A 和项目 B 之间的项目

xpath: how to select items between item A and item B

我有一个 HTML 页面结构如下:

<big><b>Staff in:</b></big>
<br>
<a href='...'>Movie 1</a>
<br>
<a href='...'>Movie 2</a>
<br>
<a href='...'>Movie 3</a>
<br>
<br>
<big><b>Cast in:</b></big>
<br>
<a href='...'>Movie 4</a>

如何使用 Xpath select 电影 1、2 和 3? 我写了这个查询

'//big/b[text()="Staff in:"]/following::a'

但它 returns 电影 1、2、3 和 4。我想我需要找到一种方法来获取 <big><b>Staff in: 之后但下一个 <big> 之前的项目。

谢谢,

假设 <big><b>Staff in:</b></big> 是一个独特的元素,我们可以将其用作 'anchor',您可以这样尝试:

//big[b='Staff in:']/following-sibling::a[preceding-sibling::big[1][b='Staff in:']]

基本上,xpath 会找到所有 <a> 上面提到的 'anchor' <big> 元素之后的兄弟元素,并将结果限制为具有最近的前一个兄弟元素的元素 <big> 等于锚元素。

xpath tester 中的输出给定有问题的标记作为输入(进行最小调整以使其格式正确 XML):

Element='<a href="...">Movie 1</a>'
Element='<a href="...">Movie 2</a>'
Element='<a href="...">Movie 3</a>'

//a[preceding::b[text()="Staff in:"] and following::b[text()="Cast in:"]]

Returns 所有 a 在元素 b 之后带有文本 Staff in: 但在元素 b 之前带有文本 Cast in:

您可能需要添加更多条件以使其更加具体,具体取决于这些 b 元素在页面上是否唯一。

只是添加并遵循 Whosebug link 这里 XPath axis, get all following nodes until 这是我使用 xslt 编辑器制定的完整解决方案。首先使用 /*/ 代替 // 因为这样更快。其次,逻辑说所有作为大节点兄弟姐妹的锚节点都将被返回,如果它们满足内部条件,即大节点的前兄弟节点等于它们后面的节点。还假设你有不同的大节点。

x 路径看起来像

/*/big[b="Cast in:"]/following-sibling::a [1 = count(preceding-sibling::big[1]| ../big[b="Cast in:"])]

xslt 解决方案看起来像

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <html>
            <body>
            <h2>My Movie Collection</h2>
            <table border="1">
                <tr bgcolor="#9acd32">
                    <th>Title</th>

                </tr>
                <xsl:variable name="placeholder" select="/*/big" />
                <xsl:for-each select="$placeholder">
                    <xsl:variable name="i" select="position()" />
                    <b>
                        <xsl:value-of select="$i" />
                        <xsl:value-of select="$placeholder[$i]" />
                    </b>
                    <xsl:for-each
                        select="following-sibling::a [1 = count(preceding- 
sibling::big[1]| ../big[b=$placeholder[$i]])]">
                        <tr>
                            <td>
                                <xsl:value-of select="." />
                            </td>

                        </tr>
                    </xsl:for-each>
                </xsl:for-each>
            </table>
        </body>
    </html>
</xsl:template>
</xsl:stylesheet>