i have an xml:
<body>
<car>
<color>green</color>
<nr>88</nr>
</car>
<car>
<color>yellow</color>
<nr>54</nr>
</car>
<car>
<color>blue</color>
<nr>89</nr>
</car>
<car>
<color>red</color>
<nr>17</nr>
</car>
<car>
<color>white</color>
<nr>64</nr>
</car>
</body>
I want to make sure that the colors are white, green, blue, yellow, red (the order doesn't matter). So i wrote a script:
import groovy.util.XmlSlurper
def pXml = new XmlSlurper().parseText('<body><car><color>green</color><nr>88</nr></car><car><color>yellow</color><nr>54</nr></car><car><color>blue</color><nr>89</nr></car><car><color>red</color><nr>17</nr></car><car><color>white</color><nr>64</nr></car></body>')
def actual = pXml.car.color.sort(true) {it.text()}
def expected = ['blue', 'green', 'red', 'white', 'yellow'].sort()
assert expected==actual
Forgive me if it looks weird, i'm new in programming. I tired it in online groovy parser and in SoapUI, but i always get:
Caught: Assertion failed:
assert expected==actual
| | |
| | [blue, green, red, white, yellow]
| false
[blue, green, red, white, yellow]
Assertion failed:
assert expected==actual
| | |
| | [blue, green, red, white, yellow]
| false
[blue, green, red, white, yellow]
at main.run(main.groovy:6)
Kindly advice
You can use a Set instead of sorting
def actual = pXml.car.color*.text() as Set
Set expected = ['blue', 'green', 'red', 'white', 'yellow']
assert expected==actual
Your problem BTW was here:
def actual = pXml.car.color.sort(true) {it.text()}
That was taking all the nodes, and sorting them by their text.
It was not returning a list of Strings, it was returning a list of Nodes.
If you want to keep using Lists, you can change this to:
def actual = pXml.car.color*.text().sort(true)
To sort the String text, instead of the Nodes
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.