问题
I need to print a certain child node of my XML which is having multiple child nodes. I have given a sample xml below. But, karate converts to json and prints the data in json format; but i need it to be returned in XML.
XML:
* def xml =
"""
<ns4:root xmlns:ns4="http://foo.com" xmlns:ns5="http://bar.com">
<ns4:Test>
<ns5:code>123</ns5:code>
<ns5:description>My Description</ns5:description>
<ns5:SubTest>
<ns6:code>345</ns6:code>
<ns6:description>Your Description</ns6:description>
<ns6:categoryCode>BH</ns6:categoryCode>
</ns5:SubTest>
<ns5:SubTest>
<ns6:code>567</ns6:code>
<ns6:description>Your Description</ns6:description>
<ns6:categoryCode>BH</ns6:categoryCode>
</ns5:SubTest>
<ns5:SubTest>
<ns6:code>784</ns6:code>
<ns6:description>Your Description</ns6:description>
<ns6:categoryCode>BH</ns6:categoryCode>
</ns5:SubTest>
<ns5:categoryCode>DUDU</ns5:categoryCode>
<ns5:unwanted>Unwanted XML Parameter</ns5:unwanted>
</ns4:Test>
<ns4:Test>
<ns5:code>675</ns5:code>
<ns5:description>His Description</ns5:description>
<ns5:unwanted>Unwanted XML Parameter</ns5:unwanted>
</ns4:Test>
</ns4:root>
"""
This is the xpath query i am using to print second SubTest node with code = 567.
* def PP_XML = $xml/root/Test/SubTest[2]/*
* print PP_XML
This gives response like this;
13:40:19.391 [ForkJoinPool-1-worker-1] INFO com.intuit.karate - [print] [
"567",
"Your Description",
"BH"
]
Is there any way i can isolate and print only second child SubTest node in proper XML?
I tried with below one too; but without luck.
* def PP_XML = $xml/root/Test/SubTest[2]
* print PP_XML
I tried elimination process as well, by excluding other 2 child nodes like below; this throws 'cannot convert to xml' error. I know this is how karate handles xml but wanna know if i can reproduce this.
* def PP_XML = $xml/root/Test/*[not(self::SubTest[1]) or (self::SubTest[3])]
* xml PP = PP_XML
* print PP
回答1:
* def PP_XML = $xml/root/Test/SubTest[2]
* print PP_XML
Gives:
15:21:24.723 [main] INFO com.intuit.karate - [print] <ns5:SubTest>
<ns6:code>567</ns6:code>
<ns6:description>Your Description</ns6:description>
<ns6:categoryCode>BH</ns6:categoryCode>
</ns5:SubTest>
Seems to work just fine.
来源:https://stackoverflow.com/questions/53665986/karate-xml-printing-child-node