Accessing child nodes in #each helper

37 views
Skip to first unread message

Brice Chidester

unread,
Jan 9, 2023, 11:36:05 AM1/9/23
to wiremock-user
We're working on simulating some services in WireMock, and are trying to find a way to use response templating to iterate over nested collections. We're specifically working with XML, but JSON will also be needed at some point.

Short version: Is there a way to access child nodes of the node being iterated over in an #each helper?

Detail:

The request has something like:
<myRequest>
  <item>
    <material>AAA</material>
    <uom>EA</uom>
  </item>
  <item>
    <material>BBB</material>
    <uom>CS</uom>
  </item>
</myRequest>

We can access the entire structure by using: 
{{#each (xPath request.body '/myRequest/item') as |node|}}text: {{{node}}}\n{{/each}}

but this just outputs the existing structure, and we need to be able to modify the item nodes. Ideally, the response would look something like:

<response>
  <item>
    <mat>AAA</mat>
    <unit>EA</unit>
    <qty>{random value}</qty>
  </item>
  <item>
    <mat>BBB</mat>
    <unit>CS</unit>
    <qty>{random value}</qty>
  </item>
</response>

So we need a way to access the values of the child nodes directly so we can build a new structure.

If anyone has any thoughts, they would be much appreciated!

Tom Akehurst

unread,
Jan 10, 2023, 6:35:52 PM1/10/23
to wiremock-user
Slightly cumbersome unfortunately but the key is to use nested XPaths like so:

<response>

  {{#each (xPath request.body '/myRequest/item') as |node|}}
  <item>
    <mat>{{xPath node '/item/material/text()'}}</mat>
    <unit>{{xPath node '/item/uom/text()'}}</unit>
    <qty>{{randomValue type='NUMERIC' length=2}}</qty>
  </item>
  {{/each}}
</response>


Reply all
Reply to author
Forward
0 new messages