2013-04-05 153 views
0

我有一个简单的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> 

所以我有两个问题:

  1. 为什么?
  2. 我该如何添加child2作为parent的子女,如果child1没有孩子?
+1

您正在使用什么版本的PHP和libxml2的吗?你的“破”的代码[适用于我](http://3v4l.org/JiGAf#v513)。 – salathe 2013-04-05 20:26:13

+0

2.7.8和5.4 =( – 2013-04-05 21:17:16

+1

在这种情况下,我给出的链接显示你的代码在5.4.0上的2.7.8正常工作。 – salathe 2013-04-05 22:41:20

回答

0

xpath()返回传递给它的元素的CHILDREN。所以,当你将addChild()添加到xpath()返回的第一个元素时,实际上是将一个子元素添加到父元素的第一个元素,即child1。当你运行该代码,哟uwill看到是正在创建一个“父子”元素作为“父”的孩子 -

<?php 
$original = new SimpleXMLElement('<root><parent><child1></child1></parent></root>'); 
$root = new SimpleXMLElement('<root><parent><child1></child1></parent></root>'); 
$parent = new SimpleXMLElement('<root><parent><child1></child1></parent></root>'); 
$child1 = new SimpleXMLElement('<root><parent><child1></child1></parent></root>'); 
$tXml = $original->asXML(); 
printf("tXML=[%s]\n",$tXml); 
$rootChild = $root->xpath('//root'); 
$rootChild[0]->addChild('rootChild'); 
$tXml = $root->asXML(); 
printf("node[0]=[%s] tXML=[%s]\n",$rootChild[0],$tXml); 
$parentChild = $parent->xpath('//parent'); 
$parentChild[0]->addChild('parentChild'); 
$tXml = $parent->asXML(); 
printf("node[0]=[%s] tXML=[%s]\n",$parentChild[0],$tXml); 
$child1Child = $child1->xpath('//child1'); 
$child1Child[0]->addChild('child1Child'); 
$tXml = $child1->asXML(); 
printf("node[0]=[%s] tXML=[%s]\n",$child1Child[0],$tXml); 
?> 

tXML=[<?xml version="1.0"?> 
<root><parent><child1/></parent></root>] 
tXML=[<?xml version="1.0"?> 
<root><parent><child1/></parent><rootChild/></root>] 
tXML=[<?xml version="1.0"?> 
<root><parent><child1/><parentChild/></parent></root>] 
tXML=[<?xml version="1.0"?> 
<root><parent><child1><child1Child/></child1></parent></root>] 
+0

只需检查你的'parentChild '实际上它不是'父'的孩子,它是'孩子1'的孩子。 – 2013-04-05 15:05:34