【发布时间】:2013-03-27 19:45:54
【问题描述】:
我有一个简单的 XML 字符串:
$sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
我尝试使用 xpath() 查找节点并将子节点添加到该节点。
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();
如您所见,child2 被添加为 child1 的子代,而不是 parent 的子代。
<root>
<parent>
<child1>
<child2></child2>
</child1>
</parent>
</root>
但如果我更改我的 XML,addChild() 效果很好。这段代码
$sample = new SimpleXMLElement('<root><parent><child1><foobar></foobar></child1></parent></root>');
$node = $sample->xpath('//parent');
$node[0]->addChild('child2');
echo $sample->asXML();
返回
<root>
<parent>
<child1>
<foobar></foobar>
</child1>
<child2>
</child2>
</parent>
</root>
所以我有两个问题:
- 为什么?
- 如果
child1没有子级,我如何将child2添加为parent的子级?
【问题讨论】:
-
您使用的是什么版本的 PHP 和 libxml2?您的“损坏”代码works for me。
-
在这种情况下,我提供的链接显示您的代码在 5.4.0 上适用于 2.7.8。
-
我只能强调salathe 已经写过的内容:您问题中的原样代码确实有效。我也无法想象为什么会发生在你身上。您可能想在添加孩子之前先进行调试,例如:
var_dump($node[0]->asXML());.
标签: php xpath simplexml addchild