xpath在关闭之前将样式分配给包含非属性但另一个标记的标记

时间:2013-04-18 23:26:15

标签: php dom xpath

大家好!

我是1门课程的学生,正在努力创造一些东西。我一直试图改变'<'li'>'的风格其中包含'<'span'>'标签和其他'<'li'>'标签应保持原样。这就是我迄今为止的方式:

<?php
$html = <<< HTML
<ul>
    <li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li><span><a href="#baz">baz</a></span></li>
</ul>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]') as $node) {
    $node->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0)); 

?>

因此导致:

<ul>
<li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li><span style="font-weight:bold; background:black;"><a href="#baz">baz</a></span></li>
</ul>

我需要实现的目标是:

<ul>
<li><span style="font-weight:bold;color:white;">foo</span></li>
    <li style="color: brown;"><a href="#bar">bar span</a></li>
    <li style="font-weight:bold; background:black;"><span><a href="#baz">baz</a></span></li>
</ul>

所以我想要设计李而不是跨度!

请帮助一个学习者,只是尝试了很多而且无法找到方法。

这是正确的方法???

<?php
$url ='http://3d.te.ua/xpath/ria.html';
$html = file_get_contents($url);
$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]') as $node) {
    $node->parentNode->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0)); 

?>

1 个答案:

答案 0 :(得分:0)

使用/..选择父节点:

$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//li[not(@style)]/span[not(@style)]/..') as $node) {
    $node->setAttribute('style', 'font-weight:bold; background:black;');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0));