PHP/SimpleXML。如何将子节点添加到xpath返回的节点?
我有一个简单的XML字符串:PHP/SimpleXML。如何将子节点添加到xpath返回的节点?,php,xpath,simplexml,addchild,Php,Xpath,Simplexml,Addchild,我有一个简单的XML字符串: $sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>'); 如您所见,child2是作为child1的子项添加的,而不是作为父项的子项添加的 <root> <parent> <child1> <child2></
$sample = new SimpleXMLElement('<root><parent><child1></child1></parent></root>');
如您所见,child2
是作为child1
的子项添加的,而不是作为父项的子项添加的
<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();
$sample=新的SimpleXMLElement(“”);
$node=$sample->xpath('//parent');
$node[0]->addChild('child2');
echo$sample->asXML();
返回
<root>
<parent>
<child1>
<foobar></foobar>
</child1>
<child2>
</child2>
</parent>
</root>
所以我有两个问题:
child1
没有子级,如何将child2
添加为parent
的子级
tXML=[
]
tXML=[
]
tXML=[
]
tXML=[
]
只需检查您的父母子女
。实际上它不是parent
的子对象,而是child1
的子对象。您使用的是什么版本的PHP和libxml2?你的“坏”代码。在这种情况下,我给出的链接显示你的代码在5.4.0版本的2.7.8版本中运行良好。我只能强调萨拉特已经编写的内容:你问题中的代码确实有效。我也无法想象为什么会发生在你身上。您可能希望在添加子项之前先进行调试,例如:var_dump($node[0]->asXML())代码>。
<root>
<parent>
<child1>
<foobar></foobar>
</child1>
<child2>
</child2>
</parent>
</root>
<?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>]