在XPath表达式中使用OR运算符

时间:2019-06-10 19:14:09

标签: php xml xpath xml-parsing domxpath

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

2 个答案:

答案 0 :(得分:1)

管道并非完全是“ OR”,它使您可以使用多个替代表达式。您可以将其与SQL中的UNION进行比较。但是它可以在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

答案 1 :(得分:0)

Normalize-space()在这里不起作用,因为您尝试查找子字符串。最好使用contains。请尝试遵循xpath。

-lQt5Sql -lQt5Core -lsqlcipher -lqsqllite -lsqlite3

基于字符串的or子句的示例。

QSqlDatabase: SQLITECIPHER driver not loaded
QSqlDatabase: available driver: SQSLITE
terminate called after throwing an instance of 'std::invalid_argument'
  what():  Driver not loaded