简体   繁体   中英

Is it possible to get XML nodes always as array even if there is only one?

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?

Example XML with only one match:

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

Resulting JSON structure:

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

Example XML with more than one match:

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

Resulting JSON structure:

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

Looking at the documentation from get , it says:

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 (eg 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.

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 eg:

* 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 } }] }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM