Delete XML nodes failing...

Please support our XML, XSLT and XPATH advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Apr 2008
Posts: 30
Reputation: Mapper99 is an unknown quantity at this point 
Solved Threads: 0
Mapper99 Mapper99 is offline Offline
Light Poster

Delete XML nodes failing...

 
-1
  #1
Oct 1st, 2009
Hi there,

I am trying to delete XML nodes using PHP. Here is a sample of my xml file.
XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. <users>
  2. <user>
  3. <fullname>PC1</fullname>
  4. <floor>4</floor>
  5. </user>
  6. <user>
  7. <fullname>PC2</fullname>
  8. <floor>3</floor>
  9. </user>
  10. </users>

Here is my code so far:

XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. <?php
  2.  
  3. $users = new DOMDocument();
  4. $users->load("officedata.xml");
  5. $suser = simplexml_load_file("officedata.xml");
  6. $count = 0;
  7.  
  8. foreach($suser->user as $user) {
  9.  
  10. if ($user['fullname'] == "PC1") {
  11. $users->documentElement->removeChild($users- documentElement->childNodes->item($count));
  12. $count--;
  13. }
  14. $count++
  15. }
  16. $users->save("officedata.xml");
  17.  
  18. ?>

Any idea why this won't work? If I remove the IF statement, all of the XML data gets removed. I am just trying to remove "PC1"

Thanks in advance,

Mapper
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 30
Reputation: Mapper99 is an unknown quantity at this point 
Solved Threads: 0
Mapper99 Mapper99 is offline Offline
Light Poster

Re: Delete XML nodes failing...

 
0
  #2
Oct 2nd, 2009
For those of you could not figure this one out, after a few tries I got it:

XML, XSLT and XPATH Syntax (Toggle Plain Text)
  1. $users = new DOMDocument();
  2. $users->load("officedata.xml");
  3.  
  4. $suser = simplexml_load_file("officedata.xml");
  5. $count = 0;
  6.  
  7. $user = $users->getElementsByTagName("user");
  8.  
  9. foreach($user as $value)
  10. {
  11. $count++;
  12. $tasks = $value->getElementsByTagName("fullname");
  13. $task = $tasks->item(0)->nodeValue;
  14.  
  15. if ($task == "PCID4") {
  16. $users->documentElement->removeChild($users->documentElement->childNodes->item($count));
  17. }
  18. }
  19.  
  20. $users->save("officedata.xml");
  21. ?>

Works like a charm and is a very useful code snippet for deleting XML records using PHP!

Mapper
http://www.freegooglewaveinvites.com
Reply With Quote Quick reply to this message  
Reply

Tags
delete, node, xml

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the XML, XSLT and XPATH Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC