在XPath中使用OR运算符

时间:2019-06-11 18:46:10

标签: php xml xpath xml-parsing domxpath

我在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>

1 个答案:

答案 0 :(得分:0)

  

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

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

包含以下字符串之一的段落为:

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()。