$content_properties
包含xpath查询的结果:<td>
包含一些简单的文本值。我想删除值等于&#34;最后查看&#34;的每个节点。所以我尝试了这个:
<?php
foreach($content_properties as $node){
if($node->nodeValue == "last viewed"){
$node->parentNode->removeChild($node);
echo "yep - ".$node->nodeValue."<br>";
}
else{
echo "nope - ".$node->nodeValue."<br>";
}
}
?>
但是当我再次回显所有$ content_properties节点值时,没有删除任何内容。
为什么我无法移除匹配的节点?我是否必须做其他事情才能删除&#39;?我不是以正确的节点为目标吗?
答案 0 :(得分:1)
您正在做的工作正常,节点已从其父节点中移除 - 它们不会从DOMNodeList $content_properties
移除。
$xml = <<<'XML'
<tr>
<td>foo</td>
<td>bar</td>
<td>last viewed</td>
<td>baz</td>
<td>last viewed</td>
</tr>
XML;
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$content_properties = $xpath->query('//td');
foreach($content_properties as $node){
if($node->nodeValue == "last viewed"){
$node->parentNode->removeChild($node);
}
}
foreach($content_properties as $node){
if($node->nodeValue == "last viewed"){
echo "yep - ".$node->nodeValue."\n";
}
else{
echo "nope - ".$node->nodeValue."\n";
}
}
echo "\n", $dom->saveXML(), "\n";
// Regen the DOMNodeList
$content_properties = $xpath->query('//td');
foreach($content_properties as $node){
if($node->nodeValue == "last viewed"){
echo "yep - ".$node->nodeValue."\n";
}
else{
echo "nope - ".$node->nodeValue."\n";
}
}
nope - foo
nope - bar
yep - last viewed
nope - baz
yep - last viewed
<?xml version="1.0"?>
<tr>
<td>foo</td>
<td>bar</td>
<td>baz</td>
</tr>
nope - foo
nope - bar
nope - baz
答案 1 :(得分:0)
这是正确的方法:
<?php
foreach($content_properties as $node){
if($node->nodeValue == "last viewed"){
$content_properties->parentNode->removeChild($node);
echo "yep - ".$node->nodeValue."<br>";
}
else{
echo "nope - ".$node->nodeValue."<br>";
}
}
?>