views:

195

answers:

1

Im having a big xml tree with a simple structure. All I want to do is get a node by its attribute using xpath and loop the children.

param1 - correct language

param1 & param3 - correct node by its id and the parents id. (Need to use parent id when multiplie id appears. The id is not declared as id in DTD)

    public function getSubmenuNodesRe($language, $id1,$id2) {
    $result = $this->xml->xpath("//*[@language='$language']//*[@id='$id1']//menuitem[@id='$id2']/*");
    return $result;
}

This works well, I get the node Im expecting. I having no problems looping the array returned by the xpath query. But when i try to loop childnodes all attributes are gone and many of the methods also. Except getName().

    function printNodeName($node) 
{
    echo $node->getName(). " - \"" . $node['id']. "\"<br>";

    if($node->children()->getName() == "menuitem")
    {
        $s = $node->children();
        printNodeName($s);
    }
}



$result = $xmlNode->getSubmenuNodesRe($_GET['language'], 'foo','bar');
if ($result) {
    while(list( , $node) = each($result)) {
        if ($node->getName() == "menuitem") { 
            printNodeName($node);
        }
    }
}

Why is that? only the name will be printed for the $s.

Really need help to solve this one, any assistance is deeply appreciated!

Thanks for your time.

A: 
if($node->children()->getName() == "menuitem")

This always invokes getName() on the first node in the result set of $node->children().

$node = new SimpleXMLElement('<doc>
  <a>1</a>
  <b>1</b>
  <c>1</c>
</doc>');

var_dump($node->children()->getName());

prints string(1) "a". So, if you're looking for <b> this doesn't work.
Depending on the structure of your xml document

foreach( $node->menuitem as $s ) {
  printNodeName($s);
}

might, e.g.

$node = new SimpleXMLElement('<container>
  <foo>...</foo>
  <menuitem id="a1">
    <foo>...</foo>
    <menuitem id="a11"><foo>...</foo></menuitem>
    <menuitem id="a12"><foo>...</foo></menuitem>
    <bar>..</bar>
  </menuitem>
  <menuitem id="a2">
    <foo>...</foo>
    <menuitem id="a21" />
  </menuitem>
</container>');
printNodeName($node);

function printNodeName($node, $indent=0) {
  echo str_repeat(' ', $indent), 
    $node->getName(), ' id:', 
    isset($node['id']) ? $node['id'] : 'none',
    "\n"
  ;

  foreach( $node->menuitem as $s ) {
    printNodeName($s, $indent+1);
  }
}

prints

container id:none
 menuitem id:a1
  menuitem id:a11
  menuitem id:a12
 menuitem id:a2
  menuitem id:a21
VolkerK