我有一个简单的XML字符串:PHP/SimpleXML。如何将子节点添加到由xpath返回的节点?
$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>
所以我有两个问题:
- 为什么?
- 我该如何添加
child2
作为parent
的子女,如果child1
没有孩子?
您正在使用什么版本的PHP和libxml2的吗?你的“破”的代码[适用于我](http://3v4l.org/JiGAf#v513)。 – salathe 2013-04-05 20:26:13
2.7.8和5.4 =( – 2013-04-05 21:17:16
在这种情况下,我给出的链接显示你的代码在5.4.0上的2.7.8正常工作。 – salathe 2013-04-05 22:41:20