Using DOM to Manage XML Documents


Using DOM you can manage an XML document by creating a DOM tree of the XML document containing standard objects. You can modify and traverse the DOM tree, and access the attributes, data, and elements of the DOM tree. You can modify the XML document by modifying the properties and methods of the objects. The DOM approach also lets you query XML documents to retrieve specific information. In addition to parsing the XML documents, the DOM approach lets you create XML documents from scratch. Methods such as add_root() and new_child() let you create nodes of DOM tree.

Using DOM to Modify a Document

You can modify the XML document using the DOM approach. Modifying a document includes various tasks , such as adding a new element, modifying the attribute value, or removing an element from the document tree. The DOM approach occupies a large amount of memory to parse documents. As a result, you can modify an XML file which is smaller in size using the DOM approach and the large XML documents using the SAX approach.

To understand how to modify XML documents using DOM, consider an XML file that stores information about a bookstore-shopping cart application, as shown in Listing 3-12:

Listing 3-12: Creating the bookcart.xml File
start example
 <?xml version="1.0" encoding="UTF-8"?> <Bookcart> <customer CID="354"> <name>John Anderson</name> </customer> <BookInfo> <book ID="1001"> <bookName>XML Bible</bookName> <author>Elliotte Rusty Harold</author> <quantity>2</quantity> <list_price>33</list_price> </book> <book ID="1002"> <bookName>XML in a Nutshell</bookName>      <author>Elliotte Rusty Harold</author>       <quantity>3</quantity>       <list_price>37</list_price>       </book> <book ID="1003"> <bookName>Advanced PHP Programming</bookName> <author>George Schlossnagle</author> <quantity>5</quantity> <list_price>40</list_price> </book> </BookInfo> </Bookcart> 
end example
 

The above listing creates an XML file that stores information about the books that are available at an online bookstore. The XML file stores information, such as book titles, book IDs, author names , quantities available, and list prices.

Listing 3-13 shows how to add information on books available in the bookcart.xml file using the DOM approach:

Listing 3-13: Adding Book to the Shopping Cart
start example
 <?php $xmlfile = "bookcart.xml"; $modfile = AddProduct($xmlfile, "1004", "XML and PHP", "William", "4", "30"); print($modfile); function AddProduct($xml, $ID, $bookName, $author, $quantity, $list_price) {    $doc = xmldocfile($xml);    $root = $doc->root();    $children = $root->children();    foreach ($children as $child)    {       if ($child->node_type() == XML_ELEMENT_NODE)       {          if ($child->tagname() == "BookInfo") {          $newbook = $doc-create_element("book");          $newbook->set_attribute("bID", $ID);          $nname = $doc-create_element("bookName");          $nametext = $doc-create_text_node($bookName);          $nname->add_child($nametext);          $nprice = $doc-create_element("list_price");          $pricetext = $doc-create_text_node($list_price);          $nprice->add_child($pricetext);          $nauthor = $doc-create_element("author");          $authortext = $doc-create_text_node($author);          $nauthor->add_child($authortext);          $nquantity = $doc-create_element("quantity");          $quantitytext = $doc-create_text_node($quantity);          $nquantity->add_child($quantitytext);          $newbook->add_child($nname);          $newbook->add_child($nprice);          $newbook->add_child($nauthor);          $newbook->add_child($nquantity);          $child->add_child($newbook);       }    } } $xml = $doc->dump_mem(); $fp = fopen("/var/www/html/add.xml", "w+"); fwrite($fp, $doc->dumpmem(), strlen($doc->dumpmem())); return $xml; } ?> 
end example
 

The above listing lets you add a new book in the online shopping cart.

You need to pass book details, such as book titles, authors, prices, and quantities as arguments to the AddProduct() function. The cart.xml file is parsed using the xmldocfile() function, and the root and child nodes are retrieved from the document. The AddProduct() function verifies the tag name property of the element node and uses the add_child() function to add new child nodes and attributes to the DOM tree. In the above listing, the dumpmem() method dumps the modified XML document into a string. Figure 3-6 shows the output of Listing 3-13:

click to expand: this figure shows the modified contents of an xml file obtained after adding details about a new book, which is added to the shopping cart using the dom approach.
Figure 3-6: Output of Adding Information about Books Available in the DOM Tree

You can also delete elements from the tree structure using the DOM parser. For example, you can delete the information about a book sold from the online shopping cart.

Listing 3-14 shows how to delete elements from the DOM tree.

Listing 3-14: Removing Tree Elements
start example
 <?php $xml_file = "bookcart.xml"; $tt=RemoveProduct($xml_file, "1003"); print($tt); function RemoveProduct($xml, $id) {    $doc = xmldocfile($xml);    $root = $doc->root();    $children = $root->child_nodes();    foreach ($children as $child)     {       if ($child->node_type() == XML_ELEMENT_NODE)          {             if ($child->tagname() == "BookInfo")             {                $BookInfo = $child->child_nodes();                foreach ($BookInfo as $book)                 {                   if ($book->node_type() == XML_ELEMENT_NODE)                    {                      $book_children = $book->child_nodes();                      $ts = $book->get_attribute("ID");                      if ($ts == $id)                      {                         $book->unlink_node();                      }                   }                }             }           }     }     $xml = $doc->dumpmem();     $fp = fopen("/var/www/html/remove.xml", "w+");     fwrite($fp, $doc->dumpmem(), strlen($doc->dumpmem()));     return $xml; } ?> 
end example
 

The above listing lets you remove the instances of a particular book from the online shopping cart. In the above listing, all the instances of the book with the book ID 1003 are removed from the cart using the unlink_node() function. Figure 3-7 shows the output of Listing 3-14:

click to expand: this figure shows the modified contents of the dom tree generated from the bookcart.xml file. the nodes containing information about the book with the book id 1003 are deleted from the dom tree.
Figure 3-7: Output of Removing Tree Elements

Using DOM to Query a Document

In addition to adding and deleting elements from the XML document tree, the DOM parser also lets you retrieve specific information from an XML document. Querying the XML documents includes the process of traversing through the XML document to search for particular elements or information. For example, you have created an XML document that stores books information, such as author names, number of pages, prices, and titles of the books available at an online bookstore, and you want to retrieve information on a specific book from the XML document. You can create a query to retrieve information from the XML document using the DOM parser.

Listing 3-15 shows how to create an XML document that stores information on books:

Listing 3-15: Creating the book.xml File
start example
 <?xml version="1.0"?> <books> <book> <title>XML in a Nutshell</title> <author>Elliotte Rusty Harold</author> <price>121</price> <pages>300</pages> </book> <book> <title>Advanced PHP Programming</title> <author>George</author> <price>161</price> <pages>150</pages> </book> <book> <title>Learning XML</title> <author>John William</author> <price>231</price> <pages>200</pages> </book> </books> 
end example
 

The above listing creates the XML file, book.xml, which stores information about books available for online shopping. The above listing lets you retrieve information, such as author names and book prices from the book.xml file, for a book titled Learning XML, with more than 100 pages.

Listing 3-16 shows how to create the query to retrieve the specified book information:

Listing 3-16: Querying the XML Document using DOM
start example
 <?php function get($domnode) {    $content = '';    foreach ($domnode->child_nodes() as $child)     {       if ($child->node_type() == XML_TEXT_NODE)        {       $content .= $child->content;       }    }    return $content;    }    $doc = xmldocfile("book.xml");    $root = $doc->document_element();    foreach ($root->child_nodes() as $element)     {       if ($element->node_type() == XML_ELEMENT_NODE and       $element->tagname() == "book")        {          $c1 = false;          $c2 = false;          foreach ($element->child_nodes() as $book_element)          {             if ($book_element->node_type() == XML_ELEMENT_NODE and             $book_element->tagname() == "title")              {             if (($title = get($book_element)) == "Learning XML")              {                $c1 = true;             }          }          if ($book_element->node_type() == XML_ELEMENT_NODE and          $book_element->tagname() == "pages")           {             if (($pages = get($book_element))>100)              {                $c2 = true;             }          }          if ($book_element->node_type() == XML_ELEMENT_NODE and          $book_element->tagname() == "author")           {             $author = get($book_element);          }          if ($book_element->node_type() == XML_ELEMENT_NODE and          $book_element->tagname() == "price")           {             $price = get($book_element);          }       }       if ($c1&& $c2)        {          print ("Author: $author Price:$price<br/>");       }    } } ?> 
end example
 

The above listing shows how to query for specific information stored in an XML document using the DOM approach.

The DOM parser traverses through the entire DOM tree to search for the nodes that fulfill the specific conditions. The listing searches for the nodes that are of the element type and then verifies the tag name and the text in the nodes. The listing displays the author name and the price of the book with the title, Learning XML with more than 100 pages.

Figure 3-8 shows the output of Listing 3-16:

click to expand: this figure shows the output obtained after querying the book.xml file using the dom parser to retrieve book information. the figure displays the author s name and the price of the book titled, learning xml that consists of more than 100 pages.
Figure 3-8: Output of Querying the XML Document

Using DOM to Write XML Data

In addition to modifying or traversing the XML document, DOM lets you create a new XML document. You can create a root node and add children to the root node to construct the DOM tree. The process of creating an XML document using the DOM parser can be used in the following instances:

  • Creating an XML file from a text file.

  • Constructing an XML document from various databases such as MySQL and MSXS.

  • Combining more than one XML document into an XML document.

  • Representing the PHP object properties in the form of an XML document.

The DOM approach provides you with various methods, such as add_root() and new_child(), which lets you create the root and text nodes of a DOM tree. For example, the add_root () method lets you add a root node to the DOM tree, and the set_attribute () method lets you set the attributes for the root node. The new_xmldoc() method lets you create a new XML document using the DOM parser.

Listing 3-17 shows how to create an XML document using the DOM parser:

Listing 3-17: Creating XML File using DOM
start example
 <?php $doc = new_xmldoc("1.0"); // Adding root node $root = $doc->add_root("Book"); // Setting attribute for the root node $root->set_attribute("Title","XML and PHP"); // Adding children to the root node $title = $root->new_child("Author","John Williams"); $author = $root->new_child("Price","145"); $date = $root->new_child("PublishingDate", date("d-M-Y", mktime())); echo $doc->dumpmem(); print "$new_xmldoc"; $fp = fopen("/var/www/html/add.xml", "w+"); fwrite($fp, $doc->dumpmem(), strlen($doc->dumpmem())); return $xml; ?> 
end example
 

The above listing creates a DomDocument object, new_xmldoc, generating the first version of an XML document. The root node, Book, and the child nodes, such as Author, Price, and PublishingDate, are added to the DomDocument object. The dumpmem () method dumps the created XML tree into a string.

Figure 3-9 shows the output of Listing 3-17:

click to expand: this figure shows the xml document created using the dom classes. the xml file contains the root node book, with child nodes such as author, price, and publishingdate.
Figure 3-9: Contents of the File Created using DOM



Integrating PHP and XML 2004
Integrating PHP and XML 2004
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 51

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net