Expects response XML to already be parsed
328920
def on_complete(env)
      env[:body] = Nori.new(
        strip_namespaces: true,
        convert_tags_to: ->(tag) { tag.snakecase.to_sym }
      ).parse(env[:body])

      raise SOAPError, "Invalid SOAP response" if env[:body].empty?

      env[:body] = env[:body][:envelope][:body]
      env[:body] = find_key_in_hash(env[:body], @key)
    end
1245170
function parseHttpResponse(options, filesWithHash) {
    if (options.verbose) {
        _utils.logger.info('Parsing HTTP responses...');
    }
    var promises = [];
    var _iteratorNormalCompletion5 = true;
    var _didIteratorError5 = false;
    var _iteratorError5 = undefined;

    try {
        for (var _iterator5 = filesWithHash[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
            var fileWithHash = _step5.value;

            if (fileWithHash.subtitlesPresent) continue;
            var p = (0, _utils.XML2JSON)(options, fileWithHash).catch(function (err) {
                if (options.verbose) {
                    _utils.logger.info('Error in HTTP response: ', err.err);
                }
                return err.fileWithHash;
            });
            promises.push(p);
        }
    } catch (err) {
        _didIteratorError5 = true;
        _iteratorError5 = err;
    } finally {
        try {
            if (!_iteratorNormalCompletion5 && _iterator5.return) {
                _iterator5.return();
            }
        } finally {
            if (_didIteratorError5) {
                throw _iteratorError5;
            }
        }
    }

    return Promise.all(promises);
}
1138812
function _parseXml( xmlStr ) {
    let doc;

    return new Promise( ( resolve, reject ) => {
        try {
            doc = libxmljs.parseXml( xmlStr );
            resolve( doc );
        } catch ( e ) {
            reject( e );
        }
    } );
}
171066
def update(self):
        """"""
        response = self.jss.session.post(self.url, data=self.auth)
        response_xml = ElementTree.fromstring(response.text.encode("utf_8"))

        # Remove previous data, if any, and then add in response's XML.
        self.clear()
        for child in response_xml.getchildren():
            self.append(child)
1247501
function processXML(name, uri, processor, resp, callback) {
  var parser = new xml2js.Parser();

  parser.parseString(resp, function (err, xml) {
    if (err) {
      GLOBAL.error(name, err);
      return;
    } else {
      processor.getAnnotations(name, uri, xml, function(err, annoRows) {
        callback(err, {name: name, uri: uri, annoRows: annoRows});
      });
    }
  });
}
1109748
def parse_posts_dates_response(body)
        dom = parse_and_validate_response(body, :root_name => 'dates')
        dom.root.get_elements('date').inject({}) do |collection, xml|
          date  = xml.if_attribute_value(:date)
          count = xml.if_attribute_value(:count)
          collection.merge({ date => count })
        end
      end
309821
protected function prepare_response() {
        try {
            if (!empty($this->function->returns_desc)) {
                $validatedvalues = external_api::clean_returnvalue($this->function->returns_desc, $this->returns);
                $encodingoptions = array(
                    "encoding" => "UTF-8",
                    "verbosity" => "no_white_space",
                    // See MDL-54868.
                    "escaping" => ["markup"]
                );
                // We can now convert the response to the requested XML-RPC format.
                $this->response = xmlrpc_encode_request(null, $validatedvalues, $encodingoptions);
            }
        } catch (invalid_response_exception $ex) {
            $this->response = $this->generate_error($ex);
        }
    }
403925
@WebMethod(name = "config.xml")
    public HttpResponse doConfigDotXml(StaplerRequest req) throws IOException {
        if (req.getMethod().equals("GET")) {
            // read
            checkPermission(READ);
            return new HttpResponse() {
                public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
                    rsp.setContentType("application/xml");
                    View.this.writeXml(rsp.getOutputStream());
                }
            };
        }
        if (req.getMethod().equals("POST")) {
            // submission
            updateByXml(new StreamSource(req.getReader()));
            return HttpResponses.ok();
        }

        // huh?
        return HttpResponses.error(SC_BAD_REQUEST, "Unexpected request method " + req.getMethod());
    }
507991
def from_post_response(post_response, content):
        '''
        
        '''
        response = OutcomeResponse()
        response.post_response = post_response
        response.response_code = post_response.status
        response.process_xml(content)
        return response
769993
private function processResponse()
    {
        $xmlstr = '';
        $record = 0;
        foreach ($this->response as $line) {
            if ($record == 1) {
                $xmlstr .= $line;
            } elseif (substr($line, 0, 1) == '<') {
                $record = 1;
            } elseif (preg_match('/^HTTP\/1.[0-9]{1} ([5-9]{1}[0-9]{2}.*)/', $line, $matches)) {

                throw new ConnectionException($this->host . ': Service not available (' . trim($matches[1]) . ')');
            }
        }
        try {
            libxml_use_internal_errors(true);
            $xml = new SimpleXMLElement($xmlstr);
        } catch (\Exception $error) {

            throw new ConnectionException($error->getMessage());
        }
        if((string)$xml->attributes()->status === 'failed' )
        {
            throw new ApiFailedException($xml->error, intval($xml->error['code']));
        }
        if (!isset($error)) {
            // All is well :)
            return $xml;
        }
    }
652886
def _parse_response(xml):
        
        try:
            soap_response = xmltodict.parse(xml, process_namespaces=True, namespaces=Service.Namespaces)
        except Exception:
            logging.debug('unable to parse the xml response: %s', xml)
            raise WSManException("the remote host returned an invalid soap response")

        # the delete response has an empty body
        body = soap_response['soap:Envelope']['soap:Body']
        if body is not None and 'soap:Fault' in body:
            raise WSManOperationException(body['soap:Fault']['soap:Reason']['soap:Text']['#text'])
        return body
494707
def xml_to_json_response(service_spec, operation, xml, result_node=None):
    """"""

    def transform(value, spec):
        """Apply transformations to make the output JSON comply with the
        expected form. This function applies:

          (1) Type cast to nodes with "type" property (e.g., 'true' to
              True). XML field values are all in text so this step is
              necessary to convert it to valid JSON objects.

          (2) Squashes "member" nodes to lists.

        """
        if len(spec) == 1:
            return from_str(value, spec)

        od = OrderedDict()
        for k, v in value.items():
            if k.startswith('@'):
                continue

            if k not in spec:
                # this can happen when with an older version of
                # botocore for which the node in XML template is not
                # defined in service spec.
                log.warning(
                    'Field %s is not defined by the botocore version in use', k)
                continue

            if spec[k]['type'] == 'list':
                if v is None:
                    od[k] = []
                elif len(spec[k]['member']) == 1:
                    if isinstance(v['member'], list):
                        od[k] = transform(v['member'], spec[k]['member'])
                    else:
                        od[k] = [transform(v['member'], spec[k]['member'])]
                elif isinstance(v['member'], list):
                    od[k] = [transform(o, spec[k]['member'])
                             for o in v['member']]
                elif isinstance(v['member'], OrderedDict):
                    od[k] = [transform(v['member'], spec[k]['member'])]
                else:
                    raise ValueError('Malformatted input')
            elif spec[k]['type'] == 'map':
                if v is None:
                    od[k] = {}
                else:
                    items = ([v['entry']] if not isinstance(v['entry'], list) else
                             v['entry'])
                    for item in items:
                        key = from_str(item['key'], spec[k]['key'])
                        val = from_str(item['value'], spec[k]['value'])
                        if k not in od:
                            od[k] = {}
                        od[k][key] = val
            else:
                if v is None:
                    od[k] = None
                else:
                    od[k] = transform(v, spec[k])
        return od

    dic = xmltodict.parse(xml)
    output_spec = service_spec.output_spec(operation)
    try:
        for k in (result_node or (operation + 'Response', operation + 'Result')):
            dic = dic[k]
    except KeyError:
        return None
    else:
        return transform(dic, output_spec)
    return None
521766
function parseResponse(xhr){
    var parsed;
    var self = this;
    if (window.karma || window.parent.karma){
        // #]*§ WTF!!
        LOG.info('TESTING MODE');
        xhr.responseType = self.options.responseType;
    }                        
    LOG.log('responseType in readyState ', xhr.responseType);                                                                                
    if (xhr.responseType === 'json' || xhr.responseType === 'arraybuffer'){
        LOG.log('JSON CASE!', xhr.response);                        
        parsed = xhr.response;
    } else if (xhr.responseType === 'document'){
        LOG.log('DOCUMENT CASE!', xhr.responseXML);
        parsed = xhr.responseXML;
    } else if (xhr.responseType === 'text' || xhr.responseType === ''){
        LOG.log('TEXT CASE!');                
        parsed = xhr.responseText;
    } else {
        LOG.log('DEFAULT CASE!', xhr.responseText);
        parsed = xhr.responseText;
    }
    
    return [parsed, xhr.status, xhr];
}
1254574
private String getBlankResponseXml() {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("requestID", UUID.randomUUID().toString());

        String ret = null;

        try {
            ret = TemplateUtils.get(BLANK_RESPONSE_TEMPLATE, data);
        } catch (AwsMockException e) {
            log.error("fatal exception caught: {}", e.getMessage());
            e.printStackTrace();
        }
        return ret;
    }
11486
function serverResponseToRESPONSE (response) {
	try {
		const obj = JSON.parse(response);
		if (obj.result === RESPONSE_UNKNOWN) {
			return RESPONSE_UNKNOWN;
		} else {
			return obj.result.result;
		}
	} catch (e) {
		return RESPONSE_INVALID;
	}
}
434609
private static Response createResponse(Object object) {
    if (object == null) {
      return Response.ok().build();
    }

    if (object instanceof Response) {
      return (Response) object;
    }

    if (object instanceof Response.Status) {
      Response.Status s = (Response.Status) object;
      switch (s) {
        case OK:
          return Response.ok().build();
        case ACCEPTED:
          return Response.accepted().build();
        case NO_CONTENT:
          return Response.noContent().build();
        default:
          return createErrorResponse(
              new S3Exception("Response status is invalid", S3ErrorCode.INTERNAL_ERROR));
      }
    }

    // Need to explicitly encode the string as XML because Jackson will not do it automatically.
    XmlMapper mapper = new XmlMapper();
    try {
      return Response.ok(mapper.writeValueAsString(object)).build();
    } catch (JsonProcessingException e) {
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
          .entity("Failed to encode XML: " + e.getMessage()).build();
    }
  }
700888
function(req, res, next) {
    // If we timed out before managing to respond, don't send the response
    if (res.headersSent) {
      return;
    }

    // Look for `.json` or `.xml` extension in path
    // And override request accept header
    if (/.json$/.test(req.path)) {
      req.headers.accept = 'application/json';
    } else if (/.xml$/.test(req.path)) {
      req.headers.accept = 'application/xml';
    }

    // Use request accept header to determine response content-type
    res.format({
      json: function() {
        res.status(res.code).jsonp(res.data);
      },
      xml: function() {
        var xml;
        try {
          var xmlData = JSON.parse(JSON.stringify(res.data));
          xml = this.xmlBuilder.buildObject(xmlData);
          res.set('Content-Type', 'application/xml; charset=utf-8');
          res.status(res.code).send(xml);
        } catch (e) {
          res.status(500).end();
        }
      }.bind(this)
    });
  }