即使只有一个XML节点,也可能始终将XML节点作为数组获得吗? [英] Is it possible to get XML nodes always as array even if there is only one?

查看:225
本文介绍了即使只有一个XML节点,也可能始终将XML节点作为数组获得吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Karate测试SOAP Web服务.方法之一是,根据请求,响应可以返回一个或多个巧合. 在将该XML响应转换为JSON时,如果只有一个结果,则将其解释为一个对象,但是如果有多个结果,则它将是一个数组.

I'm testing a SOAP webservice using Karate. One of the methods is that depending on the request, the response can return one or more coincidences. When transforming that XML response to JSON, if there is only one result, it's is interpreted as an object, but if there are more, then it's an array.

对于给定路径,是否有任何方法可以使它始终以数组形式返回?

Is there any way to make that for a given path, it is always returned as an array?

仅具有一个匹配项的XML示例:

Example XML with only one match:

<matches>
    <product>...</product>
</matches

结果JSON结构:

{ 
    matches: {
        product: ...,
    }
}

具有多个匹配项的示例XML:

Example XML with more than one match:

<matches>
    <product>...</product>
    <product>...</product>
    <product>...</product>
</matches

结果JSON结构:

{ 
    matches: [
        { product: ... },
        { product: ... },
        { product: ... },
    ]
}

查看获取中的文档,它说:

get语法支持的一种便利(但不包括$快捷形式)是:如果右侧求出类似列表的结果(例如JSON数组),则返回单个元素. 这很有用,因为在JsonPath中使用通配符[*]或搜索过滤器时(请参阅下一节),您将获得一个数组-尽管通常您只对第一项感兴趣

A convenience that the get syntax supports (but not the $ short-cut form) is to return a single element if the right-hand-side evaluates to a list-like result (e.g. a JSON array). This is useful because the moment you use a wildcard [*] or search filter in JsonPath (see the next section), you get an array back - even though typically you would only be interested in the first item.

但是我一直在努力,但没有成功.我不知道这是做到这一点的方法,还是有更好/可行的方法.

But I've been trying and did not get it to work. I don't know if that is the way to do it or there is a better/working one.

推荐答案

不幸的是,没有-这确实是空手道中XML和JSON工作方式的不同.因此,您将必须执行一些自定义逻辑.例如:

Unfortunately, no - this is indeed a difference in the way XML and JSON work in Karate. So you will have to do some custom logic. For e.g:

* def temp = { foo: { bar: { a: 1 } } }
# * def temp = { foo: [{ bar: { a: 1 } }] }
* if (temp.foo.bar) karate.set('temp', '$.foo', [temp.foo])
* match temp == { foo: [{ bar: { a: 1 } }] }

因此,如果您确定JSON必须始终是数组,那么只需一行就可以标准化" JSON.

So just 1 line can "normalize" the JSON if you are sure it always has to be an array.

这篇关于即使只有一个XML节点,也可能始终将XML节点作为数组获得吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆