Response Templating - Working with XML

This article describes MockLab’s helpers for processing and manipulating XML.


The xPath helper can be used to extract values or sub documents via an XPath 1.0 expression from an XML string. Most commonly this is used to extract values from the request body.

For example, given a request body of:


The following will render “Stuff” into the output:

{{{xPath request.body '/outer/inner/text()'}}}

And given the same XML the following will render <inner>Stuff</inner>:

{{{xPath request.body '/outer/inner'}}}

Extracting attributes

XPath also permits extraction of attributes e.g. for a request body of:

    <inner id="123"/>

The following will render “123” into the output:

{{{xPath request.body '/outer/inner/@id'}}}


As a convenience the soapXPath helper also exists for extracting values from SOAP bodies e.g. for the SOAP document:

<soap:Envelope xmlns:soap="">

The following will render “success” in the output:

{{{soapXPath request.body '/a/test/text()'}}}

Iterating over XML elements

The xPath helper returns “one or many” collections results, which can either be printed directly, or passed to further helpers such as each or join.

For instance, given a request body of the form:

<?xml version="1.0"?>

and the following template:

{{#each (xPath request.body '/stuff/thing') as |element|}}{{{element.text}}} {{/each}}

the resulting output will be:

One Two Three

XML element attributes

Elements in the collection returned by xPath have the following properties:

text: The text content of the element.

name: The element’s name.

attributes: A map of attribute names and values e.g. given an XML element has been selected:

<thing id="123" position="top"/>

Its attributes can be referenced:

      ID: {{{}}}
Position: {{{element.attributes.position}}}