Jump to content

how to reverse traverse xml


mpsn

Recommended Posts

Hi, starting at a given node, I want to be able to build a pathway from that current node all the way to the root node.

 

Let's say I have this email.xml file:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<email>

<message>

  <to>

  <toFirstName>Bob</toFirstName>

  <toLastName type="common">Smith</toLastName>

  </to>

</message>

</email>

 

Here is my script which btw is infinite loop:

<?php
$doc=new DOMDocument();
$doc->load("email.xml");
$pathway=array();
$dom1=$doc->getElementsByTagName("toLastName")->item(0);
while(!$dom1->documentElement->nodeName) {
$pathway[]=$dom1->nodeName."/".$dom1->parentNode->nodeName."/";
$strPathway=implode("",$pathway);
print $strPathway;
}
?>

The output I want is in this format:

email/message/to/toLastName (I will figure out how to use rsort since in the while loop it appends as: toLastName/to/message/email

 

Any help much appreciated!

Link to comment
Share on other sites

Now I realized I have no end condition so infinite loop, please see updated code again.

 

<?php
$pathway=array();
$strPathway="";
$dom1=$doc->getElementsByTagName("toLastName")->item(0);

while($dom1->parentNode!=NULL) {
$dom1=$dom1->parentNode;//NEW: update $dom1
$pathway[]=$dom1->nodeName."/".$dom1->parentNode->nodeName."/";
}
$strPathway=implode("",$pathway);
print $strPathway;
?>

So my code ALMOST works, but I get this notice. I guess the most top level is document which HAS NO PARENTS so how do I indicate that once current node is now the actual document to stop.

 

Any help much appreciated!

Notice: Trying to get property of non-object in

to/message/message/email/email/#document/#document//

Link to comment
Share on other sites

As you can see above, for some reason, in browser output, it is ALMOST correct except that it is printing whatever the current node's parent, two times:

 

Notice: Trying to get property of non-object

to/message/message/email/email/#document/#document//

 

Actually it's b/c I update $dom1=$dom1->parentNode, BUT I'm still unsure as to why it is printing #document, how do I use break once I'm at the root?

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.