DOM replaceChild不替换所有指定的元素 [英] DOM replaceChild not replacing all specified elements
问题描述
考虑以下代码:
$xml = <<<XML
<root>
<region id='thisRegion'></region>
<region id='thatRegion'></region>
</root>
XML;
$partials['thisRegion'] = "<p>Here's this region</p>";
$partials['thatRegion'] = "<p>Here's that region</p>";
$DOM = new DOMDocument;
$DOM->loadXML($xml);
$regions = $DOM->getElementsByTagname('region');
foreach( $regions as $region )
{
$id = $region->getAttribute('id');
$partial = $DOM->createDocumentFragment();
$partial->appendXML( $partials[$id] );
$region->parentNode->replaceChild($partial, $region);
}
echo $DOM->saveXML();
输出为:
<root>
<p>Here's this region</p>
<region id="thatRegion"/>
</root>
我一生都无法弄清为什么所有区域标签都没有被替换。这是我项目中的一个问题,起初我以为这不是替换我在loadXML之后附加的元素,但是经过一些试验,我无法在此处缩小模式。
I cannot for the life of me figure out why all of the region tags aren't being replaced. This is a problem in my project, and at first I thought that it wasn't replacing elements I appended after the loadXML, but with some experimenting I haven't been able to narrow down the pattern here.
我希望对代码进行更正,以允许我用给定的Element Node替换DOMDocument中的所有标签。如果找不到,我也不会介意以更有效/更实用的方式执行此操作。
I would appreciate a code correction to allow me to replace all tags in a DOMDocument with a given Element Node. I also wouldn't mind any input into a more efficient/practical way to execute this if I haven't found it.
在此先感谢!
PHP 5.3.13
[edit] PHP 5.3.13
推荐答案
NodeList处于活动状态。
因此,当您删除文档中的项目时,NodeList也将被修改。避免使用对NodeList的引用并在最后一项开始替换:
NodeLists are live. So when you remove an item inside the document, the NodeList also will be modified. Avoid using a reference to the NodeList and start replacing at the last item:
$DOM = new DOMDocument;
$DOM->loadXML($xml);
$regions = $DOM->getElementsByTagname('region');
$regionsCount = $DOM->getElementsByTagName('region')->length;
for($i= $regionsCount;$i>0;--$i)
{
$region=$DOM->getElementsByTagName('region')->item($i-1);
$id = $region->getAttribute('id');
$partial = $DOM->createDocumentFragment();
$partial->appendXML( $partials[$id] );
$region->parentNode->replaceChild($partial, $region);
}
echo $DOM->saveXML();
?>
这篇关于DOM replaceChild不替换所有指定的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!