我想在我的 XPath 表达式中使用 OR 条件(不止一次)在遇到特定字符串之前提取我需要的内容,例如“参考”、“更多信息”等。我在下面的表达式当我在 PHP 中使用它时似乎不起作用,但它在 XPath 测试仪上运行。我将不胜感激任何帮助。另外,表达可以压缩吗?
"//p[starts-with(normalize-space(),'Reference')]/preceding-sibling::p |
//p[starts-with(normalize-space(), 'For more')]/preceding-sibling::p |
//p[starts-with(normalize-space(),'Something')]/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 given the nation's booming economy
and the hundreds of millions of dollars that city, county and
state officials have directed toward the problem.
</p>
<p>
"We cannot let a set of difficult numbers discourage us
or weaken our resolve" Garcetti said.
</p>
<p>
For more information: Maeve Reston, CNN
</p>
</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 given the nation's booming economy
and the hundreds of millions of dollars that city, county and
state officials have directed toward the problem.
</p>
<p>
"We cannot let a set of difficult numbers discourage us
or weaken our resolve" Garcetti said.
</p>
管道不完全是“或”——它允许您使用多个替代表达式。您可以将其与UNION
SQL 中的进行比较。但它适用于 PHP。
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$expression =
"//p[starts-with(normalize-space(), 'Reference')]/preceding-sibling::p |
//p[starts-with(normalize-space(), 'For more')]/preceding-sibling::p |
//p[starts-with(normalize-space(), 'Something')]/preceding-sibling::p";
foreach ($xpath->evaluate($expression) as $node) {
echo $document->saveXML($node);
}
但是,在 Xpath 条件下允许使用“或”,实际上:
$expression =
"//p[
starts-with(normalize-space(), 'Reference') or
starts-with(normalize-space(), 'For more') or
starts-with(normalize-space(), 'Something')
]/preceding-sibling::p";
foreach ($xpath->evaluate($expression) as $node) {
echo $document->saveXML($node);
}
演示:https : //3v4l.org/9SMJq
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句