首页 > 解决方案 > 在 XPath 中使用 OR 运算符

问题描述

我在我的 XPath 表达式中使用 OR 运算符(不止一次)在遇到特定字符串之前提取我需要的内容,例如“参考”、“更多信息”等。这些术语中的任何一个都应该返回相同的结果,但它们可能不是该顺序。例如,“参考”可能不是第一个,也可能根本不在内容中,其中一个匹配项使用了“关于数据”表。我想要在这些字符串中的任何一个出现之前的所有内容。

任何帮助,将不胜感激。

$expression =
    "//p[
        starts-with(normalize-space(), 'Reference') or 
        starts-with(normalize-space(), 'For more')
    ]/preceding-sibling::p";

这还需要考虑到表格:

$expression =
    "//article/table/tbody/tr/td[
        starts-with(normalize-space(), 'About the data used')
]/preceding-sibling::p";

这是一个例子:

<root>
    <main>
        <article>
            <p>
                The stunning increase in homelessness announced in Los Angeles
                this week — up 16% over last year citywide — was an almost an
                incomprehensible conundrum.
            </p>
            <p>
                "We cannot let a set of difficult numbers discourage us
                or weaken our resolve" Garcetti said.
            </p>
            <p>
                References
                By Jeremy Herb, Caroline Kelly and Manu Raju, CNN
            </p>
            <p>
                For more information: Maeve Reston, CNN
            </p>
            <p>Maeve Reston, CNN</p>
            <table>
                <tbody>
                    <tr>
                        <td>
                            <strong>About the data used</strong>
                        </td>
                    </tr>
                    <tr>
                        <td>From
                        </td>
                        <td>Washington, CNN</td>
                    </tr>
                </tbody>
            </table>
        </article>
    </main>
</root>

我正在寻找的结果如下。

<p>
    The stunning increase in homelessness announced in Los Angeles
    this week — up 16% over last year citywide — was an almost  an
    incomprehensible conundrum.
</p>
<p>
    "We cannot let a set of difficult numbers discourage us
    or weaken our resolve" Garcetti said.
</p>

标签: phpxmlxpathxml-parsingdomxpath

解决方案


我想要在这些字符串中的任何一个出现之前的所有内容。

也就是说,您希望第一段之前的内容包含其中一个字符串。

包含这些字符串之一的段落是:

p[starts-with(normalize-space(), 'References') or starts-with(....)]

第一个这样的段落是

p[starts-with(normalize-space(), 'References') or starts-with(....)][1]

之前的段落是:

p[starts-with(normalize-space(), 'References') or starts-with(....)][1]
/preceding-sibling::p

在 2.0 中,我可能会使用正则表达式:

p[matches(., '^\s*(References|For more information)')]

以避免对 normalize-space() 的重复调用。


推荐阅读