我有一个简单的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>
所以我有两个问题:
- 为什么?
- 我怎么能添加
child2
作为parent
的孩子,如果child1
没有孩子?
xpath()返回传递给它的元素的CHILDREN。因此,当对xpath()返回的第一个元素添加addChild()时,实际上是在向parent的第一个元素添加一个子元素,即child1。当您运行这段代码时,您将看到它正在创建一个"parentChild"元素作为"parent"的子元素-
<?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>]