【发布时间】:2015-11-18 03:04:49
【问题描述】:
我正在尝试在 php 版本 5.6.11 中使用 SimpleXMLIterator 以 BFS 顺序迭代 XML 树。但是,我发现它只是遍历嵌套在级别 1 的 XML 元素,就在级别 0 的根节点下方,跳过级别 2、3、...的所有嵌套元素。
那么如何让迭代器以 BFS 方式遍历 XML 树?
PHP documentation 提到迭代器应该是递归的。代码如下:
<?php
function getXMLCode() {
$xmlCode = <<<XML
<home>
<livingroom>
<sofa>
<leftPillow></leftPillow>
<rightPillow></rightPillow>
</sofa>
<television></television>
</livingroom>
<bedroom>
<bed>
<sheet></sheet>
<duvet></duvet>
<pillow></pillow>
</bed>
</bedroom>
<bathroom>
<sink></sink>
<toilet></toilet>
<bath>
<bathtap></bathtap>
</bath>
</bathroom>
<kitchen>
<fridge>
<lettuce>
<snail></snail>
</lettuce>
</fridge>
</kitchen>
</home>
XML;
return $xmlCode;
}
function test() {
$xmlCode = getXMLCode();
$simpleXMLIterator = new SimpleXMLIterator($xmlCode);
foreach ($simpleXMLIterator as $xmlElement) {
echo $xmlElement->getName(), "\n";
}
}
test();
这里是输出,如上所述,它不构成 BFS 遍历(加上根节点也被省略了):
输出:
livingroom
bedroom
bathroom
kitchen
预期输出:
home
livingroom
bedroom
bathroom
kitchen
sofa
television
bed
sink
toilet
bath
fridge
leftPillow
rightPillow
sheet
duvet
pillow
bathtap
lettuce
snail
【问题讨论】: