E4X Voorbeelden

E4X makes scripting for XML exceptionally simple.

E4X Voorbeelden

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)

Of course, 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>

Omgaan met gegevens:

Bereken prijs:

var total=order.item.qty * order.item.price

Toon volledige klantnaam:

document.write(order.customer.lastname)
document.write(",")
document.write(order.customer.firstname)

Voeg nieuw item toe:

order.item+/
<item>
  <name>Pavlova</name>
  <qty>10</qty>
  <price>128.00</price>
</item>

Toon ordernummer:

document.write(order.@id)

Als er meerdere artikelen in de order zijn, bereken dan het totaalbedrag:

var price=0
for each (i in order.item)
  {
  price+= i.qty*i.price
  }