WebReference.com - Part 2 of Chapter 10 from Professional PHP4 XML, from Wrox Press Ltd (1/4)
[next] |
Professional PHP4 XML, Chapter 10: Putting It Together
Modifying XML
[The following is a continuation of our series of excerpts from chapter 10 of the Wrox Press title, Professional PHP4 XML. Source code for the examples discussed can be downloaded at the Wrox Web site (free e-mail registration required).]
Modifying XML is a problem where we have an XML data source and need to modify it. We may want to change some text, add an attribute, add an element, or remove a subtree of the document.
Modifying is a subset of the transforming problem since the output is always XML, and belongs to the same vocabulary as the original file.
Here are some situations where we might find instances of this problem:
- Using XML data as a catalog and then having to add/modify/remove items from the catalog
- Using XML to keep statistics that need to be updated
- Using XML for logging and having to add data
Example
For example, let's imagine we use XML to keep track of a shopping cart in some online store application. We may face a simple XML such as:<cart>
<user uid="382378">
<name>John Smith</name>
</user>
<products>
<product pid="12">
<name>ACMEPencilHB</name>
<desc>Soft Pencil by ACME</desc>
<quantity>2</quantity>
<unit_price>0.50</unit_price>
</product>
<product pid="13">
<name>ACMEPen089</name>
<desc>Rollerball pen</desc>
<quantity>1</quantity>
<unit_price>1</unit_price>
</product>
</products>
</cart>
Customers will use an interface to add/remove products from the shopping cart, and we have to reflect those changes to the XML file. Therefore, we'll need a way to:
Add a product
Given thepid(product ID),<name>,<desc>,<quantity>, and<unit_price>. We'll add the product to the cart; if the product already exists in the cart we don't change it, we add it to the end.Remove a product
Given thepid, we remove all instances of the product from the cart.
Of course we should need more functions for our shopping cart to be usable, but let's use only these three for our examples.
When modifying XML is our task, the options are:
- DOM
- SAX
- XSLT
[next] |
Created: August 19, 2002
Revised: August 19, 2002
URL: http://webreference.com/programming/php/php4xml/chap10/2/


