Karate DSL: Extract XML attribute value from the response [duplicate] - karate

This question already has an answer here:
Karate assert - I'm trying to extract a value from HTML
(1 answer)
Closed 1 year ago.
I am getting response as below:
How to extract value of attribute xmlns as "https://www.w3schools.com/xml/"?
def response =
"""
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
soap:Body
37.7777777777778
</soap:Body>
</soap:Envelope>
"""

Sometimes it is better to convert to JSON. Try this example:
* def response =
"""
<soap:Envelope xmlns:soap="schemas.xmlsoap.org/soap/envelope" xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema"> <soap:Body> <FahrenheitToCelsiusResponse xmlns="w3schools.com/xml"> <FahrenheitToCelsiusResult>37.7777777777778</FahrenheitToCelsiusResult> </FahrenheitToCelsiusResponse> </soap:Body> </soap:Envelope>
"""
* json response = response
* def ns = response['soap:Envelope']['_']['soap:Body'].FahrenheitToCelsiusResponse['#'].xmlns
* match ns == 'w3schools.com/xml'
Now you will be able to get any attribute you want.
Also read this: https://github.com/intuit/karate#print - especially the part about internally XML being JSON so if you don't print correctly, you won't see what you want.

Related

DHL CreateShipmentOrder XML API

I'm trying to integrate the DHL CreateShipmentOrder API.
When I send the document prepared by DHL with the Soap UI program, it works correctly.
My code and the returned result are as follows.
When I contacted DHL, I could not reach the result. Can you help me ?
I'm trying to integrate the DHL CreateShipmentOrder API.
When I send the document prepared by DHL with the Soap UI program, it works correctly.
My code and the returned result are as follows.
When I contacted DHL, I could not reach the result. Can you help me ?
My Code;
public static void Main()
{
// Create Web request to get title elements
var serviceUrl = "https://cig.dhl.de/services/production/soap";
HttpWebResponse response = null;
try
{
String sPayload = String.Format(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:cis='http://dhl.de/webservice/cisbase' xmlns:ns='http://dhl.de/webservices/businesscustomershipping/3.0'>
<soapenv:Header>
<cis:Authentification>
<cis:user>*****</cis:user>
<cis:signature>*******</cis:signature>
</cis:Authentification>
</soapenv:Header>
<soapenv:Body>
<ns:CreateShipmentOrderRequest>
<ns:Version>
<majorRelease>3</majorRelease>
<minorRelease>1</minorRelease>
</ns:Version>
<ShipmentOrder>
<sequenceNumber/>
<Shipment>
<ShipmentDetails>
<product>V01PAK</product>
<cis:accountNumber>********</cis:accountNumber>
<customerReference>Ref. 123456</customerReference>
<shipmentDate>2022-01-06</shipmentDate>
<ShipmentItem>
<weightInKG>5</weightInKG>
<lengthInCM>60</lengthInCM>
<widthInCM>30</widthInCM>
<heightInCM>15</heightInCM>
</ShipmentItem>
<Notification> <recipientEmailAddress>empfaenger#test.de</recipientEmailAddress>
</Notification>
</ShipmentDetails>
<Shipper>
<Name>
<cis:name1>Absender Zeile 1</cis:name1>
<cis:name2>Absender Zeile 2</cis:name2>
<cis:name3>Absender Zeile 3</cis:name3>
</Name>
<Address>
<cis:streetName>Vegesacker Heerstr.111</cis:streetName>
<cis:zip>28757</cis:zip>
<cis:city>Bremen</cis:city>
<cis:Origin>
<cis:country/>
<cis:countryISOCode>DE</cis:countryISOCode>
</cis:Origin>
</Address>
<Communication>
<!--Optional:-->
<cis:phone>+49421987654321</cis:phone>
<cis:email>absender#test.de</cis:email>
<!--Optional:-->
<cis:contactPerson>Kontaktperson Absender</cis:contactPerson>
</Communication>
</Shipper>
<Receiver>
<cis:name1>Empfänger Zeile 1</cis:name1>
<Address>
<cis:name2>Empfänger Zeile 2</cis:name2>
<cis:name3>Empfänger Zeile 3</cis:name3>
<cis:streetName>An der Weide 50a</cis:streetName>
<cis:zip>28195</cis:zip>
<cis:city>Bremen</cis:city>
<cis:Origin>
<cis:country/>
<cis:countryISOCode>DE</cis:countryISOCode>
</cis:Origin>
</Address>
<Communication>
<cis:phone>+49421123456789</cis:phone>
<cis:email>empfaenger#test.de</cis:email>
<cis:contactPerson>Kontaktperson Empfänger</cis:contactPerson>
</Communication>
</Receiver>
</Shipment>
<PrintOnlyIfCodeable active='1'/>
</ShipmentOrder>
<labelResponseType>URL</labelResponseType>
<combinedPrinting>0</combinedPrinting>
</ns:CreateShipmentOrderRequest>
</soapenv:Body>
</soapenv:Envelope>");
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(serviceUrl) as HttpWebRequest;
webRequest.ContentType = "text/xml;charset=utf-8";
webRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes("******:*****"));
webRequest.Method = "POST";
using (var sw = new StreamWriter(webRequest.GetRequestStream()))
{
sw.Write(sPayload);
sw.Close();
}
response = (HttpWebResponse) webRequest.GetResponse();
}
catch (WebException ex)
{
Console.WriteLine("Exception: " + ex.Message);
}
finally
{
if (response != null)
Console.WriteLine("Http status = " + response.StatusCode + " - " + response.StatusDescription);
}
if( response != null && response.StatusDescription == "OK" ) {
Console.WriteLine("Successfull");
}
Console.WriteLine(DateTime.Now.ToString());
}
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>SECURITY_VIOLATION</faultstring>
</soap:Fault>
</soap:Body>
</soap:Envelope>
In order to communicate with DHL, it is imperative to use the DHL WSDL files and accesses. (Download at https://developer.dhl.de/)
Benjamin Müller gives the answer to your question under the following link. It is best to use the latest WSDL from DHL, a few objects (actually only names) still have to be adjusted.
Java WSDL DHL Classes
The two lines below the following line must be used, otherwise the authentication will not work.
// overwrite BasicAuth Username and Password
This is the only way DHL will not reject the request with "SECURITY_VIOLATION".
All other ways are not approved by DHL and lead to an error message.

Remove Characters from XML Output in Postman

I'm making an XML API call in Postman and I get the following response:
<response>
<result>
<system>YYY:XXXXXXXXX</system>
</result>
</response>
I created a variable from the content in "system", but I need to remove the "YYY:" from the front. Here is how I created the variable:
var response = xml2Json(responseBody);
var uuid = response["response"]["result"]["system"];
pm.collectionVariables.set("uuid", uuid);
If that could be formatted to remove any possible other characters before the colon - ex: "CCC:" or "ABC:" or "VAR1:" - that would be a bonus, but hard-coding this to remove exactly "YYY:" would solve the current problem.
You could do this, split String by character ":"
let text = "YYY:XXXXXXXXX";
console.log(text.split(":")[1]);
Apply to your code:
var response = xml2Json(responseBody);
var uuid = response["response"]["result"]["system"];
pm.collectionVariables.set("uuid", uuid.split(":")[1]);
Result:

Oracle extractValue returns invalid token

I have this query which fails on this extract value
EXTRACTVALUE(xmltype(REQUEST), '/soapenv:Envelope/soapenv:Body/ns2:getCustomerRequestRetrieve/ns2:requestHeader/ns5:referenceID', 'xmlns:soapenv:http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns8="ca/bell/oms/autotype/customerrequestretrieve" xmlns:ns2="ca/bell/oms/autotype/customerrequestretrieve"') RequestReferenceID
Somewhere i am setting the wrong path. can you let me know where i am making a error
The actual XML is
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<ns2:getCustomerRequestRetrieve xmlns = "ca/bell/oms/autotype/omscommonresponse"
xmlns:ns5 = "sa/cell/oms/autotype/omscommonrequest"
xmlns:ns2 = "sa/cell/oms/autotype/customerrequestretrieve"
xmlns:ns3 = "sa/cell/oms/autotype/omscommon"
xmlns:ns4 = "sa/cell/oms/customerprofile">
<ns2:requestHeader>
<ns5:customerInteractionType>CustomerNotification</ns5:customerInteractionType>
<ns5:serviceRequestUserId>null</ns5:serviceRequestUserId>
<ns5:serviceConsumer>khg</ns5:serviceConsumer>
<ns5:serviceRequestTimestamp>2019-02-05T03:50:12.000-05:00</ns5:serviceRequestTimestamp>
<ns5:language>English</ns5:language>
<ns5:referenceID>Tjutrf7T78H4</ns5:referenceID>
<ns5:transactionIdentifier>eed7ffe0-da22-498f-9913-c2279d1549356612606</ns5:transactionIdentifier>
</ns2:requestHeader>
<ns2:searchCriteria>
<ns2:requestIdentifier>
<ns2:orderNumber>TTjutrf7T8H4</ns2:orderNumber>
</ns2:requestIdentifier>
</ns2:searchCriteria>
<ns2:filterCriteria>
<ns2:fullOrderDetail>ContactOnly</ns2:fullOrderDetail>
</ns2:filterCriteria>
</ns2:getCustomerRequestRetrieve>
</soapenv:Body>
</soapenv:Envelope>
enter code here
You have mistakes in namespaces declaration.
EXTRACTVALUE(REQUEST, '/soapenv:Envelope/soapenv:Body/ns2:getCustomerRequestRetrieve/ns2:requestHeader/ns5:referenceID'
,'xmlns:soapenv=http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns2="sa/cell/oms/autotype/customerrequestretrieve"
xmlns:ns5="sa/cell/oms/autotype/omscommonrequest"
') RequestReferenceID
Moreover EXTRACTVALUE function is deprecated. Replacemnet for it is xmlquery,xmltable.
select xmlcast(xmlquery('declare namespace soapenv="http://schemas.xmlsoap.org/soap/envelope/";
declare namespace ns2="sa/cell/oms/autotype/customerrequestretrieve";
declare namespace ns5="sa/cell/oms/autotype/omscommonrequest";
/soapenv:Envelope/soapenv:Body/ns2:getCustomerRequestRetrieve/ns2:requestHeader/ns5:referenceID/text()' passing xmltype(request) returning content) as varchar2(100)) from ....;

Karate - [#document: null] in output

I have used regular expression to remove few unwanted items in my XML. Now, I need to print all includedService nodes which contain multiple child elements inside.
Here's code i used;
* string test = read('classpath:PP1/data/Test.xml')
* string test= test.replaceAll("xsi:nil[^/]*", "")
* def Complete_XML = test
* def included = $Complete_XML/Envelope/Body/getPricePlanResponse/pricePlanSummary/includedService
* print included
If i run this, I get below response.
20:19:54.169 [ForkJoinPool-1-worker-1] INFO com.intuit.karate - [print] [
[#document: null],
[#document: null]
]
However, I can print selected elements outside of includedService node. Please help!
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Header/>
<S:Body>
<ns10:getPricePlanResponse>
<ns10:pricePlanSummary>
<ns5:descriptionFrench>Forfait Montre Affaires</ns5:descriptionFrench>
<ns4:category/>
<ns4:effectiveDate>2009-11-05</ns4:effectiveDate>
<ns4:serviceDataSharingGroupList>
<ns4:dataSharingGroupCode>CAD_DATA</ns4:dataSharingGroupCode>
<ns4:contributingInd>true</ns4:contributingInd>
</ns4:serviceDataSharingGroupList>
<ns4:feature>
<ns5:descriptionFrench>Service</ns5:descriptionFrench>
<ns4:poolGroupId/>
</ns4:feature>
<ns4:recurringCharge>10.0</ns4:recurringCharge>
<ns4:ppsStorageSize>0</ns4:ppsStorageSize>
<ns4:includedService>
<ns4:term>0</ns4:term>
<ns4:brandId>1</ns4:brandId>
<ns4:feature>
<ns5:code>MBAPN</ns5:code>
<ns4:type/>
<ns4:additionalNumberRequiredInd>false</ns4:additionalNumberRequiredInd>
</ns4:feature>
<ns4:recurringCharge>0.0</ns4:recurringCharge>
<ns4:callingCircleFeaturesInd>false</ns4:callingCircleFeaturesInd>
</ns4:includedService>
<ns4:includedService>
<ns4:term>0</ns4:term>
<ns4:brandId>1</ns4:brandId>
<ns4:feature>
<ns5:code>MBAPN</ns5:code>
<ns4:type/>
<ns4:additionalNumberRequiredInd>false</ns4:additionalNumberRequiredInd>
</ns4:feature>
<ns4:recurringCharge>0.0</ns4:recurringCharge>
<ns4:callingCircleFeaturesInd>false</ns4:callingCircleFeaturesInd>
</ns4:includedService>
<ns4:availableTermInMonths>0</ns4:availableTermInMonths>
</ns10:pricePlanSummary>
</ns10:getPricePlanResponse>
</S:Body>
</S:Envelope>
Keep in mind XML always has to be wrapped inside some element or the other. Try this:
* def included = $xml/Envelope/Body/getPricePlanResponse/pricePlanSummary//includedService
* def root = <root></root>
* def fun = function(x, i){ karate.set('root', '/includedService[' + (i + 1) + ']', x) }
* eval karate.forEach(included, fun)
* print root
You should get:
<root>
<ns4:includedService>
<ns4:term>0</ns4:term>
<ns4:brandId>1</ns4:brandId>
<ns4:feature>
<ns5:code>MBAPN</ns5:code>
<ns4:type/>
<ns4:additionalNumberRequiredInd>false</ns4:additionalNumberRequiredInd>
</ns4:feature>
<ns4:recurringCharge>0.0</ns4:recurringCharge>
<ns4:callingCircleFeaturesInd>false</ns4:callingCircleFeaturesInd>
</ns4:includedService>
<ns4:includedService>
<ns4:term>0</ns4:term>
<ns4:brandId>1</ns4:brandId>
<ns4:feature>
<ns5:code>MBAPN</ns5:code>
<ns4:type/>
<ns4:additionalNumberRequiredInd>false</ns4:additionalNumberRequiredInd>
</ns4:feature>
<ns4:recurringCharge>0.0</ns4:recurringCharge>
<ns4:callingCircleFeaturesInd>false</ns4:callingCircleFeaturesInd>
</ns4:includedService>
</root>
For other ideas, refer this answer: https://stackoverflow.com/a/53553979/143475

force.com streaming API

I am trying the Force.com Streaming API demo and I get the following error:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body><soapenv:Fault>
<faultcode>UNKNOWN_EXCEPTION</faultcode>
<faultstring>UNKNOWN_EXCEPTION: Element type "soapenv:Envelope" must be followed by either attribute specifications, ">" or "/>". </faultstring>
<detail>
<sf:UnexpectedErrorFault xsi:type="sf:UnexpectedErrorFault">
<sf:exceptionCode>UNKNOWN_EXCEPTION</sf:exceptionCode>
<sf:exceptionMessage>Element type "soapenv:Envelope" must be followed by either attribute specifications, ">" or "/>".</sf:exceptionMessage>
</sf:UnexpectedErrorFault>
</detail>
</soapenv:Fault></soapenv:Body>
</soapenv:Envelope>
Line 22 has a misplaced double quote that is not caught by your compiler.
Replace this code:
private static final String ENV_START =
"
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:urn='urn:partner.soap.sforce.com'><soapenv:Body>";
With this code:
private static final String ENV_START =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'"
+ "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:urn='urn:partner.soap.sforce.com'><soapenv:Body>";