E4X Examples
- Previous Page E4X Browser
- Next Page E4X Tutorial
E4X makes scripting for XML exceptionally simple.
E4X Examples
As an example, we will deal with an XML document representing an order.
The XML document looks something like this:
<order> <date>2005-08-01</date> <customer> <firstname>John</firstname> <lastname>Johnson</lastname> </customer> <item> <name>Maxilaku</name> <qty>5</qty> <price>155.00</price> </item> </order>
If we store this XML document in a string named txt, we can load it into an XML object named order by writing the following JavaScript statement:
var order = new XML(txt)
Or we can directly assign a value to this XML object variable using an XML document:
var order = new XML() order = <order id="555"> <date>2005-08-01</date> <customer> <firstname>John</firstname> <lastname>Johnson</lastname> </customer> <item> <name>Maxilaku</name> <qty>5</qty> <price>155.00</price> </item> </order>
Dealing with data:
Calculate the price:
var total = order.item.qty * order.item.price
Display the full name of the customer:
document.write(order.customer.lastname) document.write(",") document.write(order.customer.firstname)
Add new item:
order.item += <item> <name>Pavlova</name> <qty>10</qty> <price>128.00</price> </item>
Display order number:
document.write(order.@id)
If there are multiple items in the order, calculate the total price:
var price = 0 for each (i in order.item) { price += i.qty * i.price }
- Previous Page E4X Browser
- Next Page E4X Tutorial