/*
Given a response object determine if it's some kind of XML
320464
function isXML(res) {
  return (res.headers['content-type'] &&
          (/^[a-zA-Z]+\/xml/.test(res.headers['content-type']) ||
           /^[a-zA-Z]+\/[a-zA-Z]+\+xml/.test(res.headers['content-type'])));

}
1214214
function isElement(value) {
  return isNonNullObject(value) && value.nodeType === 1 && toString.call(value).indexOf('Element') > -1;
}
1269348
public function seeResponseIsXMLRPC()
    {
        $result = xmlrpc_decode($this->response);
        \PHPUnit\Framework\Assert::assertNotNull($result, 'Invalid response document returned from XmlRpc server');
    }
840017
def is_valid_xml_char(self, char):
        """"""
        codepoint = ord(char)
        return (0x20 <= codepoint <= 0xD7FF or
                codepoint in (0x9, 0xA, 0xD) or
                0xE000 <= codepoint <= 0xFFFD or
                0x10000 <= codepoint <= 0x10FFFF)
1297983
def get_xml_type(val):
    """"""
    if type(val).__name__ in ('str', 'unicode'):
        return 'str'
    if type(val).__name__ in ('int', 'long'):
        return 'int'
    if type(val).__name__ == 'float':
        return 'float'
    if type(val).__name__ == 'bool':
        return 'bool'
    if isinstance(val, numbers.Number):
        return 'number'
    if type(val).__name__ == 'NoneType':
        return 'null'
    if isinstance(val, dict):
        return 'dict'
    if isinstance(val, collections.Iterable):
        return 'list'
    return type(val).__name__
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
988415
function verifyAssertion($responseXmlString,$rootcert) 
   {
      date_default_timezone_set("UTC");
      if (file_exists("/tmp/xml")) {
         $tempFileDir="/tmp/xml/";          
      
      } else {
             mkdir("/tmp/xml",0777);   
         $tempFileDir="/tmp/xml/";
      }
      
      $tempName = 'saml-response-' . $this->samlCreateId() . '.xml';
      $tempFileName=$tempFileDir.$tempName;
      while (file_exists($tempFileName)) 
         $tempFileName = 'saml-response-' . $this->samlCreateId() . '.xml';

      if (!$handle = fopen($tempFileName, 'w')) {
         return false;
      }

      if (fwrite($handle, $responseXmlString) === false) {
         return false;
      }

      $p=xml_parser_create();
      $result=xml_parse_into_struct($p,$responseXmlString,$vals,$index);
      xml_parser_free($p);
      $cert_info=$index["X509CERTIFICATE"];
      $conditions=$index["CONDITIONS"];
      foreach($cert_info as $key=>$value){
         file_put_contents($tempFileName.'.cert',$vals[$value]['value']);
      }
      $cert=$tempFileName.'.cert';
      $before=0;
      $after=0;
      foreach($conditions as $key=>$value){
         $before=$vals[$value]['attributes']['NOTBEFORE'];
         $after=$vals[$value]['attributes']['NOTONORAFTER'];
      }
      $before=$this->validSamlDateFormat($before);
      $after=$this->validSamlDateFormat($after);
      if(strtotime("now") < $before || strtotime("now") >= $after){
         unlink($tempFileName);
         unlink($cert);
         return false;
      }
      fclose($handle);
      $cmd = 'xmlsec1 --verify --pubkey-cert ' . $cert .'--trusted '.$rootcert. ' '.$tempFileName.'* 2>&1 1>/dev/null';
      exec($cmd,$resp);
      if(strcmp($resp[0],"FAIL") == 0){
         $value = false;
      }elseif(strcmp($resp[0],"ERROR") == 0){
         $value = false;
      }elseif(strcmp($resp[0],"OK") == 0){
         $value = TRUE;
      }
      unlink($tempFileName);
      unlink($cert);
      return $value;
   }
544176
private static boolean isAppXml(final String mime) {
        return mime != null
                && (mime.equals("application/xml") || mime.equals("application/xml-dtd") || mime.equals("application/xml-external-parsed-entity") || mime
                        .startsWith("application/") && mime.endsWith("+xml"));
    }
375298
def is_response(cls, response):
        ''''''
        if 'css' in response.fields.get('content-type', '').lower():
            return True

        if response.body:
            # Stylesheet mistakenly served as HTML
            if 'html' in response.fields.get('content-type', '').lower():
                return cls.is_file(response.body)
961926
@Override
    boolean equivalentXml(Object target) {
        boolean result = false;

        if (target instanceof XML) {
            //    TODO    This is a horrifyingly inefficient way to do this so we should make it better.  It may also not work.
            return this.node.toXmlString(getProcessor()).equals( ((XML)target).node.toXmlString(getProcessor()) );
        } else if (target instanceof XMLList) {
            //    TODO    Is this right?  Check the spec ...
            XMLList otherList = (XMLList) target;

            if (otherList.length() == 1) {
                result = equivalentXml(otherList.getXML());
            }
        } else if (hasSimpleContent()) {
            String otherStr = ScriptRuntime.toString(target);

            result = toString().equals(otherStr);
        }

        return result;
    }
1149405
def looks_like_xml(text):
    """"""
    if xml_decl_re.match(text):
        return True
    key = hash(text)
    try:
        return _looks_like_xml_cache[key]
    except KeyError:
        m = doctype_lookup_re.match(text)
        if m is not None:
            return True
        rv = tag_re.search(text[:1000]) is not None
        _looks_like_xml_cache[key] = rv
        return rv
870111
private function extractXml($response)
    {
        /**
         * Ugly way of seeing if an attachment is present in the response.
         */
        if (strpos($response, 'application/xop+xml') === false) {
            return array($response, array('data' => null, 'mimeType' => null));
        } else {
            return $this->extractXmlAndAttachment($response);
        }
    }
770514
def object2xml(self, data):
        
        """
        if not self.__options['encoding']:
            self.set_options(encoding=self.__encoding)

        if self.__options['header_declare']:
            self.__tree.append(self.build_xml_header())

        root = self.__options['root']
        if not root:
            assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
                'if root not specified, the data that dict object and length must be one required.'
            root, data = data.items()[0]

        self.build_tree(data, root)
        xml = unicode(''.join(self.__tree).strip())

        if self.__options['encoding'] != self.__encoding:
            xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
        return xml
324768
private String clientResponseToString(ClientResponse response) {
        if (response == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[status: ").append(response.getStatus());
        builder.append(", media type: ").append(response.getType());
        if (response.getStatus() != 404) {
            try {
                String responseBody = response.getEntity(String.class);
                if (responseBody != null) {
                    builder.append(", response body: ").append(responseBody);
                }
            } catch (RuntimeException ignore) {
                // Ignore if there is no response body, or IO error - it may have already been read in certain scenario.
            }
        }
        builder.append(", response headers: ").append(response.getHeaders());
        builder.append("]");
        return builder.toString();
    }
633277
def xmlresponse(py_data):
    
    xroot = ElementTree.Element('methodResponse')
    xparams = ElementTree.SubElement(xroot, 'params')
    xparam = ElementTree.SubElement(xparams, 'param')

    type_map = {'bool': 'boolean',
                'float': 'double',
                'str': 'string',
                'unicode': 'string',
                'datetime': 'dateTime.iso8601',
                'date': 'date.iso8601',
                'time': 'time.iso8601'}

    def xobj(xparent, py_obj):
        # convert a list of information
        if type(py_obj) in (tuple, list):
            xarr = ElementTree.SubElement(xparent, 'array')
            xdata = ElementTree.SubElement(xarr, 'data')
            for val in py_obj:
                xval = ElementTree.SubElement(xdata, 'value')
                xobj(xval, val)

        # convert a dictionary of information
        elif type(py_obj) == dict:
            xstruct = ElementTree.SubElement(xparent, 'struct')
            for key, val in py_obj.items():
                xmember = ElementTree.SubElement(xstruct, 'member')
                xname = ElementTree.SubElement(xmember, 'name')
                xname.text = key
                xval = ElementTree.SubElement(xmember, 'value')
                xobj(xval, val)

        # convert a None value
        elif py_obj is None:
            ElementTree.SubElement(xparent, 'nil')

        # convert a basic value
        else:
            typ = type(py_obj).__name__
            typ = type_map.get(typ, typ)
            xitem = ElementTree.SubElement(xparent, typ)

            # convert a datetime/date/time
            if isinstance(py_obj, datetime.date) or \
                    isinstance(py_obj, datetime.time) or \
                    isinstance(py_obj, datetime.datetime):

                if py_obj.tzinfo and pytz:
                    data = py_obj.astimezone(pytz.utc).replace(tzinfo=None)
                    xitem.text = data.isoformat()
                else:
                    xitem.text = py_obj.isoformat()

            # convert a boolean
            elif type(py_obj) == bool:
                xitem.text = nstr(int(py_obj))

            # convert a non-string object
            elif not type(py_obj) in (str, unicode):
                xitem.text = nstr(py_obj)

            # convert a string object
            else:
                xitem.text = py_obj

    xobj(xparam, py_data)
    projex.text.xmlindent(xroot)
    return ElementTree.tostring(xroot)
490945
function(response, options) {
        if(options.callback) {
            var request = response.priv;

            // ensure that we have an xml doc
            var data = request.responseXML;
            if(!data || !data.documentElement) {
                data = request.responseText;
            }
            
            var obj = this.format.read(data) || {};
            
            response.insertIds = obj.insertIds || [];
            if (obj.success) {
                response.code = OpenLayers.Protocol.Response.SUCCESS;
            } else {
                response.code = OpenLayers.Protocol.Response.FAILURE;
                response.error = obj;
            }
            options.callback.call(options.scope, response);
        }
    }
432918
function toXML(obj) {
  var xml = ''
  for (var prop in obj) {
    xml += `<${prop}>${obj[prop]}</${prop}>`
  }
  return xml
}