Using FOREACH Loops

Example XML – It is assumed the default (/element) was chosen as the XPath in Step 2.

<root>
 <elements>
  <element>
   <id>1</id>
   <images>
    <img url='1-1.jpg'>My Caption</img>
    <img url='1-2.jpg'>Another Caption</img>
    <img url='1-3.jpg'>We will use these for alt text</img>
    <img url='1-4.jpg'>More text</img>
   </images>
  </element>
 </element>
</root>

Here’s an example import template where FOREACH is used to loop through each img element in the above XML.

[FOREACH({images/img})]
<img src="{@url}" alt="{.}" />
[ENDFOREACH]

Passing {images/img} to the FOREACH means we will loop through each element matching that XPath. To get this XPath, just drag one of the matching elements from the XML tree on the right to the post content box. You’ll get something like {images/img[1]}. Just remove the [1] and you’re good to go.

Inside the FOREACH loop, the XPath is relative. You can’t access “higher-level” elements inside the FOREACH loop.

{@url} will return the url attribute of the element you are looping through.
{.} will return the value of the element you are looping through – in this case, each img.
{element_name} will return the value of the element_name child element of the element you are looping through.