After reading this article you will know:
- Howto create a loop using XML data
Looping through XML
Save the following XML as an XML file and upload this to a record. Then proceed with the tutorial.
<?xml version="1.0" encoding="UTF-8"?>
<Info xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
The example XML contains multiple clients and their pets. We will loop through this XML and save this data into models Client and Pet.
First, create an action for the model that contains the XML file. Then create a text expression variable which reads the file. Our file property is called XML. We use the following expression:
Then create a collection through which we are going to loop. We will have to loop through all clients. We achieve this by using the following expression in the collection:
xpath(var:readfile, '/Info/Clients/Client', true)
- xpath() - Lets us select parts from the XML
- var:readfile - Is the variable we created in which the file is read
- '/Info/Clients/Client' - Is the part from the XML we need. (All clients)
- true - Tells the variable to ignore any other attributes in the XML (like xmlns="value").
Create a loop event in which you loop through the created collection. Don't forget to set the index variable name, as we are going to need this later.
Create a create event in the loop. Add the following text expression variable to get the name of the client:
xpath(var:readfile, '/Info/Clients/Client[' + var:index + ']/Name/text()', true)
- [index] - Selects the client using the index number, this makes sure every loop uses the next client from the XML
- /text() - This removes the XML tags from the value. <Name>John</Name> --> John
Create another loop in the loop to get the pets, once again, don't forget to set the index variable. Create a collection for the pets using the following expression:
xpath(var:readfile, '/Info/Clients/Client[' + var:index + ']/Pets/Pet', true)
Next, create a create event in the new loop. In this event we will get the pet name and save this. Create a text expression using the following expression:
xpath(var:readfile, '/Info/Clients/Client[' + var:index + ']/Pets/Pet[' + var:petindex + ']/text()', true)
Assign the variable to a property and save. Your action is now finished and should create both clients and pets.