Response Templating - Working with XML
Working with XML
This article describes WireMock Cloud’s helpers for processing and manipulating XML.
XPath
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:
And given the same XML the following will render <inner>Stuff</inner>
:
Extracting attributes
XPath also permits extraction of attributes e.g. for a request body of:
The following will render “123” into the output:
SOAP XPath
As a convenience the soapXPath
helper also exists for extracting values from SOAP bodies e.g. for the SOAP document:
The following will render “success” in the output:
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:
and the following template:
the resulting output will be:
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:
Its attributes can be referenced:
Formatting XML
The formatXml
helper allows you to output XML in either a pretty or a compact format. The default is pretty:
emits:
Whereas
emits
The xml to format can also be supplied as a block body: