An Example of Using the DOM
We would like to convert the prices in the XML file shown in Listing 16.13 to Canadian dollars.
Listing 16.13 Prices to Be Converted
1: <?xml version="1.0"?> 2: <books> 3: <book id="TY1"> 4: <title> Teach Yourself C++ in 21 Days, Second Edition 5: </title> 6: <author>Jesse Liberty 7: </author> 8: <price unit="USA">29.99 9: </price> 10: </book> 11: <book id="MJ"> 12: <title>Maximum Java 1.1 13: </title> 14: <author>Glenn Vanderburg 15: </author> 16: <price unit="USA">49.99 17: </price> 18: </book> 19: <book id="JS"> 20: <title>JavaScript Unleashed, Second Edition 21: </title> 22: <author>Richard Wagner 23: </author> 24: <price unit="USA">49.99 25: </price> 26: </book> 27: <book ID="TY2"> 28: <title> Teach Yourself Visual C++ 5 in 21 Days, Fourth Edition 29: </title> 30: <author>Nathan Gurewich 31: </author> 32: <author>Ori Gurewich 33: </author> 34: <price unit="USA">35.00 35: </price> 36: </book> 37: </books>
Listing 16.14 shows a piece of JavaScript using the DOM to convert the U.S. prices to Canadian dollars.
Listing 16.14 JavaScript for Conversion to Canadian Dollars
1: //var xml holds the Document Object
2: var priceElements = xml.getElementsByTagName("price");
3: //returns a NodeList of all elements with the tag price
4: var i;
5: for (i=0;i < priceElements.size;i++) { // looping over all those price
elements
6: var USAprice = parseFloat(priceElements.item(i)
.firstChild.nodeValue);
7: //the firstChild property returns the Text node
8: //of this Text node we take the nodeValue, being the text itself
9: //we convert this text to a number (floating)
10: priceElements.item(i).setAttribute("unit","Canadian dollar");
11: //we set the attribute "unit" to value "Canadian dollar"
12: var convertedprice = USAprice * 1.4;
13: //we convert the price to Canadian dollar
14: var newprice = xml.createTextNode(convertedprice);
15: //we create a new Text node containing the new price
16: priceElements.item(i).replaceChild(newprice,
priceElements.item(i).firstChild);
17: //we replace the old Text node with the new one
18: }
19:
| On line 2 of Listing 16.14 we make a Nodelist object containing all the elements in our XML document with the tag name price. |
For each of those elements (loop on line 5), we take the first child (firstChild property), a text node. From this text node we take the value (nodeValue property), the content. This content is converted to a number by the ParseFloat() function in JavaScript. The resulting number is used to calculate the price in Canadian dollars (line 12).
On line 14 we create a new text node, using the createTextnode() method of the document object.
This Text node is used (line 16) to replace the old text node.