XML Parser

Navigating XML

In addition to parsing an XML document an providing a simple way to traverse all of its elements, ASDK also provides the capability to navigate directly to an XML element or attribute. This allows you to extract only the required data from a document instead of dealing with it as a monolithic data set.

In the example below, instead of traversing all of the elements within the purchase order document, the code will extract only the ship to address.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import asdk.*;
import asdk.xml.*;
var xmlUrl = "http://www.themidnightcoders.com/asdk/purchaseorder.xml";
Document.load( xmlUrl, getShipToAddress );

function getShipToAddress( document )
{
  var purchaseOrder = document.getRoot();
  var shipTo = purchaseOrder.getElement( "shipTo" );
  var name = shipTo.getString( "name" );
  var street = shipTo.getString( "street" );
  var city = shipTo.getString( "city" );
  var state = shipTo.getString( "state" );
  var zip = shipTo.getString( "zip" );

  var country = shipTo.getAttribute( "country" ).getValue();

  trace( "name = " + name );
  trace( "street = " + street );
  trace( "city = " + city );
  trace( "state = " + state );
  trace( "zip = " + zip );
  trace( "country = " + country );
}

In this example, the getShipToAddress is only concerning with shipping information. To accomplish direct access to an element within an XML document, the getElement method is called (line 9), passing the name of the element to retrieve. This method returns an asdk.xml.Element object if there is a child element corresponding the name that is passed in, or undefined if an element does not exist there. In addition, lines 10 through 14 demonstrate the use of the getString method that returns the text of a child element that corresponds to the name parameter that is passed into the method call.

Note also that the country attribute of the shipTo element is also available directly from the element object by using the getAttribute method. Line 16 demonstrates this with a compond method call that gets the attribute object (getAttribute) and the gets its value (with getValue).

Running the example above yields the following lines in the output window of the Flash IDE

1
2
3
4
5
6
name = Alice Smith
street = 123 Maple Street
city = Mill Valley
state = CA
zip = 90952
country = US