php - 在 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>
解决方案
我想要在这些字符串中的任何一个出现之前的所有内容。
也就是说,您希望第一段之前的内容包含其中一个字符串。
包含这些字符串之一的段落是:
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() 的重复调用。
推荐阅读
- python - 将任意角度转换为区间 [ -pi , pi ]
- ruby-on-rails - 为什么 Rails 4.2 应用程序在运行 rake db:migrate 任务期间使用 Ansible 在 Ubuntu 服务器上部署时创建具有 root 权限的日志文件
- javascript - __doPostback Javascript 函数导致连续回发
- asp.net-core - 如何使用本地 Active Directory 在 .Net Core 3.1 Razor Pages Web 应用程序中对用户进行身份验证
- javascript - 有没有办法在 keystone 初始化后在运行时创建 Keystone 列表?
- javascript - 忽略 JavaScript 副本上的子元素
- mongodb - 使用 $group 进行聚合以获取第一个元素(有条件)
- javascript - 在 REACT 中提升消息
- ansible - Ansible playbook 为目录中的每个子目录运行命令
- pandas - 根据 pandas 中的 groupby shift 创建新列