AMPscript Looping

This example shows how to loop through xml payloads using AMPscript. We’ll break this process into few different steps.

  1. Review the xml data structured.
  2. Review the data extension.
  3. Writing logic that loads the xml into the email.
  4. Write logic to include safeguards for error handling.
  5. Write logic to loop through xml nodes.
  6. Review the code output.

Reviewing the XML Data Structure

The goal is to write AMPscript logic that will loop through all nodes. This is a screenshot of what the XML payload looks like. You’ll notice that the entire <catalog> contains multiple <book> nodes that we’ll eventually loop through with AMPscript. Additionally, you’ll also notice that for every <book> node it contains data for that specific book’s ID, Author, Title, and Genre. You can download the sample data for this tutorial by clicking here.


Reviewing the Data Extension

The goal is to write AMPscript logic that will load and loop through this XML from within the email. You’ll notice that we have three use cases mocked up below. The 2nd and 3rd use case represent negative test scenarios. This means that our AMPscript safeguards should raise an error whenever there is missing and or incomplete data. You can download the sample data for this tutorial by clicking here.

  1. Subscriber with complete XML data.
  2. Subscriber with no XML data.
  3. Subscriber with incomplete XML data.

Looping through XML with AMPscript

This example shows you how you can loop through XML with AMPscript. In this example you’ll notice that we are doing the following:

  1. Taking the XML data from the [XML] field in the sendable DE and assigning that to a variable called @XML
  2. Write AMPscript logic that uses the BuildRowSetFromXML() function to then build rows based on however many <book> nodes are available.
  3. Write AMPscript logic that sets up safeguards to handle missing XML data.
  4. Write AMPscript logic that sets up safeguards to handle incomplete XML data.
  5. Write AMPscript logic so that the the BuildRowSetFromXML() function and the AMPscript for loop only run if the XML data exists.

Gallery