deepaksharma

DPH to strip off xml tags/namespaces etc from request xml payload and further conversion of cleaned xml to JSON

Discussion created by deepaksharma on Aug 21, 2015
Latest reply on Aug 25, 2015 by IamAbhi

Request side: DPH

 

This script cleans off XML payload by removing XML namespaces/tags etc., and then converts the stripped off XML into JSON as the request payload to VS.

import org.json.XML;


public  String removeXmlStringNamespaceAndPreamble(String xmlString) {
     xmlString = xmlString.replaceAll("(?s)<(\\w+):Envelope[^<>]*>.*?<\\1:Body>\\s*(.*?)\\s*</\\1:Body>\\s*</\\1:Envelope>", "$2");
    
       return xmlString.replaceAll("(<\\?[^<]*\\?>)?", ""). /* remove preamble */
       replaceAll(" *soapenv.*?(\"|\').*?(\"|\')", ""). /* remove encodingstyle declaration */
       replaceAll("xmlns.*?(\"|\').*?(\"|\')", ""). /* remove xmlns declaration */
       replaceAll("encodingStyle.*?(\"|\').*?(\"|\')", "") /* remove encodingstyle declaration */
       .replaceAll("xsi.*?(\"|\').*?(\"|\')", "") /* remove xsi declaration */
       .replaceAll("  soapenc:arrayType=.*?(\"|\').*?(\"|\')", "") /* remove xsi declaration */
       .replaceAll("(<)(\\w+:)(.*?>)", "$1$3") /* remove opening tag prefix */
       .replaceAll("(</)(\\w+:)(.*?>)", "$1$3") /* remove closing tags prefix */
     .replaceAll("(<)(\\w+:)(.*?>)", "$1$3");
 
 
}

String theBody = lisa_vse_request.getBodyText();


if(theBody.contains("<soapenv:")||theBody.contains("Envelope")||theBody.contains("xmlns")){
 
  theBody = removeXmlStringNamespaceAndPreamble(theBody);
      String jsonresult = theBody;
      JSONObject backtojs = XML.toJSONObject(jsonresult);
      jsonresult = backtojs.toString();
 
  lisa_vse_request.setBodyText(jsonresult);
  }

Outcomes