如何在WireMock JSON映射中传递XML请求动态值到响应XML
WireMock实现XML请求参数传递到响应模板
要实现把请求XML里的RelationId值动态替换到响应XML中,需要从启用响应模板、修正XPath语法、正确引用命名空间这几个点调整,具体操作如下:
1. 启用响应模板功能
在你的WireMock映射JSON中,必须添加transformers字段开启响应模板,否则模板语法不会生效:
{ "request": { "method": "POST", "url": "/getrelation", "bodyPatterns": [ { "matchesXPath": "//ns:RelationId[contains(text(), '0123')]", "xPathNamespaces": { "ns": "http://www.example.com/XY/getRelationRequest/3/Req" } } ] }, "response": { "status": 200, "bodyFileName": "getRelationResponse.xml", "headers": { "Content-Type": "text/xml" }, "transformers": ["response-template"] // 新增这行开启模板 } }
注:原来的
matchesXPath语法有误,contains()需要两个参数,修正为contains(text(), '0123');如果不需要匹配特定值,只想匹配存在RelationId元素,可改成//ns:RelationId。
2. 修正响应XML的模板语法
你之前的模板没生效,核心问题是没有在XPath函数中指定请求XML的命名空间。修改getRelationResponse.xml中的RelationId节点,使用带命名空间参数的xPath函数:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> <soapenv:Body> <rpy:getRelationRequest_Rpy xmlns:rpy="http://www.example.com/XY/getRelationRequest/3/Rpy"> <rpy:Relations> <rpy:Relation> <rpy:RelationId>{{{xPath request.body '//ns:RelationId/text()' 'ns=http://www.example.com/XY/getRelationRequest/3/Req'}}}</rpy:RelationId> </rpy:Relation> </rpy:Relations> </rpy:getRelationRequest_Rpy> </soapenv:Body> </soapenv:Envelope>
关键修正点:
- 用
//ns:RelationId/text()直接提取元素的文本内容,比[text()]更简洁准确 - 在
xPath函数末尾添加命名空间参数:'ns=http://www.example.com/XY/getRelationRequest/3/Req',和请求中的命名空间保持一致 - 使用三重大括号
{{{...}}}避免HTML转义,确保XML内容正常输出
3. 验证逻辑
当WireMock收到带有ns:RelationId元素的POST请求时,会自动提取该元素的文本值,替换响应XML中的模板占位符,返回包含对应RelationId的XML响应。
内容的提问来源于stack exchange,提问作者user21852260
相关产品推荐
相关产品推荐

