PHP/SimpleXML. How to add child to node returned by xpath? -


i have simple xml string:

$sample = new simplexmlelement('<root><parent><child1></child1></parent></root>'); 

and try find node xpath() , add child node.

$node = $sample->xpath('//parent'); $node[0]->addchild('child2'); echo $sample->asxml(); 

as see child2 added child of child1, not child of parent.

<root>   <parent>     <child1>       <child2></child2>     </child1>   </parent> </root> 

but if change xml, addchild() works great. code

$sample = new simplexmlelement('<root><parent><child1><foobar></foobar></child1></parent></root>'); $node = $sample->xpath('//parent'); $node[0]->addchild('child2'); echo $sample->asxml(); 

returns

<root>   <parent>     <child1>       <foobar></foobar>     </child1>     <child2>     </child2>   </parent> </root> 

so have 2 questions:

  1. why?
  2. how can add child2 child of parent, if child1 has no child?

xpath() returns children of element passed it. so, when addchild() first element xpath() returns, adding child first element of parent, child1. when run code, yo uwill see is creating "parentchild" element child of "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>] 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -