繁体   English   中英

如何在标签和一些结束标签之间使用 XPath 提取文本

[英]How to extract the text using XPath between tag and some end tag

我给出了以下 HTML。 class 名称始终相同。 只有标签之间的文本有所不同,并且具有不同的长度和内容。

<a>
    <span class="xxx">Not this text <span class="yyy">not this text</span> <span class="zzz">This is</span> the required text <q class="aaa">this not</q></span>
</a>

如何提取带有 class "zzz" 的标签和行尾之间的内容,但结果中不应包含带有 class "aaa" 的元素? 可能吗?

带有 class "aaa" 的元素可能存在或不存在:

<a>
    <span class="xxx">Not this text <span class="yyy">not this text</span> <span class="zzz">This is</span> the required text</span>
</a>

预期的结果应该是:

This is the required text 

“所需文本”部分也可能存在或不存在:

<a>
    <span class="xxx">Not this text <span class="yyy">not this text</span> <span class="zzz">This is</span></span>
</a>

所以结果应该是:

This is

我使用 DOMXPath 在 PHP 中尝试这个。

XPath解决方案:

$xml = <<<'XML'
<a><span class="xxx">Not this text <span class="yyy">not this text</span> <span class="zzz">This is</span> the required text</span></a>
XML;
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$elements = $xpath->query('//text()[parent::*[not(@class="aaa")]][preceding::span[@class="yyy"]][normalize-space()]');
foreach($elements as $element)
echo $element->nodeValue;

Output:

This is the required text

我不知道如何使用 XPath 来做到这一点,但这是一种没有 XPath 的方法。

function walk(DOMNode $node, $skipParent = false) {
    if (!$skipParent) {
        yield $node;
    }
    if ($node->hasChildNodes()) {
        foreach ($node->childNodes as $n) {
            yield from walk($n);
        }
    }
}

$html = <<<'HTML'
<span class="xxx">
    Not this text
    <span class="yyy">not this text</span>
    <span class="zzz">This is</span>
    the required text
    <q class="aaa">this not</q>
</span>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$count = 0;
foreach(walk($dom->firstChild) as $node) {
    if (!($node instanceof DOMText) && $node->hasAttribute('class') && $node->getAttribute('class') === 'xxx') {
        foreach(walk($node) as $n) {
            if (isset($content)) {
                $count++;
            }
            if (!($n instanceof DOMText) && $n->hasAttribute('class') && $n->getAttribute('class') === 'zzz') {
                $content = $n->textContent;
            }
            if (isset($content) && $n instanceof DOMText && $count == 2) {
                $content .= " " . $n->textContent;
                break 2;
            }
        }
    }
}

var_dump($content);

无论"the required text"部分是否存在,这都会为您提供所需的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM