AMPscript Looping
This example shows how to loop through xml payloads using AMPscript. We’ll break this process into few different steps.
- Review the xml data structured.
- Review the data extension.
- Writing logic that loads the xml into the email.
- Write logic to include safeguards for error handling.
- Write logic to loop through xml nodes.
- 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.
- Subscriber with complete XML data.
- Subscriber with no XML data.
- 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:
- Taking the XML data from the [XML] field in the sendable DE and assigning that to a variable called @XML
- Write AMPscript logic that uses the BuildRowSetFromXML() function to then build rows based on however many <book> nodes are available.
- Write AMPscript logic that sets up safeguards to handle missing XML data.
- Write AMPscript logic that sets up safeguards to handle incomplete XML data.
- Write AMPscript logic so that the the BuildRowSetFromXML() function and the AMPscript for loop only run if the XML data exists.
Hi Everyone! Feel free to pull the full code from the link below. I hope this helps.
Looping through XML with AMPscript (Advanced Level)
https://gist.github.com/nmaratasdev/8406c3797864b6b80aa8f9f1f5e36b95
Hello, thanks for sharing you knowledge with us, I got a question, how the AMPscript will know of what DataExtension I want to use ? thanks in advance
Hi Marcos, thank you for your comment. So for this tutorial, you’ll want to create a test sendable data extension that has a text field called XML. We then stuff the payload inside the [XML] field which is included in the sendable data extension. The string that says “SET @XML = [XML]” takes the payload from that field and assigns it to a variable called @XML. The AMPscript logic then parses through that data. I hope this feedback helps, good luck!