#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2011
    Posts
    18
    Rep Power
    0

    Adding nodes to XML


    I am adding nodes to an XML file. Here is the structure.

    Code:
    <COMMUNITIES>
       <COMMUNITY ID="c001">
            <URLS>
                <URL ID="u001">
                    <NAME>Google.com</NAME>
                    <URL>http://www.google.com</URL>
                </URL>
            </URLS>
       </COMMUNITY> 
    </COMMUNITIES>
    I want to update the URLS node to add a new URL.

    Code:
           <URL ID="u002">
                     <NAME>Yahoo.com</NAME>
                     <URL>http://www.yahoo.com</URL>
             </URL>
    Here is the PHP script.

    Code:
    function add_url( $nodeid, $urlid, $urlname, $urllink ) {
    
    $dom = new DOMDocument();
    $dom->load('communities.xml');
    
    $dom->formatOutput = true; 
    $dom->preserveWhiteSpace = true;
    
    // get document element  
    
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query("//COMMUNITY[@ID='$nodeid']"); 
    
    if ($nodes->length) {
       $node = $nodes->item(0); 
    
       $xurl = $dom->createElement("URL"); 
       $xurl->setAttribute("ID", $urlid);
    
       $xuname     = $dom->createElement("NAME");  
       $xunameText = $dom->createTextNode(mysql_escape_mimic($urlname));  
       $xuname->appendChild($xunameText); 
    
       $xulink     = $dom->createElement("URL");  
       $xulinkText = $dom->createTextNode(mysql_escape_mimic($urllink));  
       $xulink->appendChild($xulinkText); 
    
       $xurl->appendChild($xuname); 
       $xurl->appendChild($xulink); 
    
       $xurls = $xpath->query("//COMMUNITY[@ID='$nodeid']/URLS");
    
       if ($xurls->length) {
       }
       else {
          $xurls = $dom->createElement("URLS"); 
       }
    
       $xurls->appendChild($xurl);
    
    }
    
    /* $dom->asXML('communities.xml'); */
    $dom->save('communities.xml');
    }
    The function runs through. The variables coming in are OK. The calls to appendChild don't cause errors. So I am wondering what might be the problem.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2011
    Posts
    18
    Rep Power
    0
    The problem was that I was adding nodes to a short tagged node, e.g. <URLS/>. This "empty" node was created by a function ealier. If I create this node in add_url() just before adding the nodes it contains, then the new nodes are added and everything works.

IMN logo majestic logo threadwatch logo seochat tools logo