Working with XML Data

Salesforce B2C Commerce JavaScript supports the E4X extension to JavaScript. This extension supports the direct manipulation of XML data in scripts, without the need to work DOM or other intermediate structures. It's standardized as ECMA-357.

  1. Specify the following:
    var order = <order><item
    quantity="1">Apple<item><item
    quantity="2">Peach<item></order>
  2. You can read values from an XML object the same way you would from standard ECMAScript objects:
    var items = order.item;
    var item = order.item(0);
    var quantity = order.item(0)[email protected];
    var singleItem = order.item.(@quantity == 1);
  3. You can also directly modify an XML object:
    var order.item += <item
    quantity="1">Orange</item>;var order.item += <item
    quantity={quantity}>Orange</item>;delete order.item(2);

Calling an Amazon.Com Service

As a working example, the next section shows how to call an amazon.com service. Amazon supports Web Service-based calls and REST calls. REST services can be called as a straight URL and return XML. The XML language support is used here to parse the returned result from the amazon.com service.

See the Amazon Simple Services Developer's Guide (www.docs.amazonwebservices.com) for more information on developing Web Services for Amazon.

// send the http request to amazon.com
var httpSvc = new HTTPClient();
httpSvc.open( "GET",
	"http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&" +
	"SubscriptionId=YOUR-SUBSCRIPTION-ID&Operation=ItemSearch&" +
	"SearchIndex=Video&Keywords=potter%20harry&ResponseGroup=Images",
	false,
	null,
	null );
httpSvc.send();
// convert the result into an XML object
var result = new XML( httpSvc.text );
// print some values from the result.
// We must use namespace qualified access to read the values.
var ns = new Namespace(
	"http://webservices.amazon.com/AWSECommerceService/2005-07-26" );
trace( result.ns::Items.ns::Request.ns::IsValid );
trace( result.ns::Items.ns::TotalResults );
trace( result.ns::Items.ns::Item[0].ns::ASIN );

If you don't see a result, validate that amazon.com still returns data with the same XML format, particularly with the same namespace identifier.