Extract arguments and their values from a SOAP response.

        Args:
            xml_response (str):  SOAP/xml response text (unicode,
                not utf-8).
        Returns:
             dict: a dict of ``{argument_name: value}`` items.
427090
def unwrap_arguments(xml_response):
        

        # A UPnP SOAP response (including headers) looks like this:

        # HTTP/1.1 200 OK
        # CONTENT-LENGTH: bytes in body
        # CONTENT-TYPE: text/xml; charset="utf-8" DATE: when response was
        # generated
        # EXT:
        # SERVER: OS/version UPnP/1.0 product/version
        #
        # <?xml version="1.0"?>
        # <s:Envelope
        #   xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
        #   s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
        #   <s:Body>
        #       <u:actionNameResponse
        #           xmlns:u="urn:schemas-upnp-org:service:serviceType:v">
        #           <argumentName>out arg value</argumentName>
        #               ... other out args and their values go here, if any
        #       </u:actionNameResponse>
        #   </s:Body>
        # </s:Envelope>

        # Get all tags in order. Elementree (in python 2.x) seems to prefer to
        # be fed bytes, rather than unicode
        xml_response = xml_response.encode('utf-8')
        try:
            tree = XML.fromstring(xml_response)
        except XML.ParseError:
            # Try to filter illegal xml chars (as unicode), in case that is
            # the reason for the parse error
            filtered = illegal_xml_re.sub('', xml_response.decode('utf-8'))\
                                     .encode('utf-8')
            tree = XML.fromstring(filtered)

        # Get the first child of the <Body> tag which will be
        # <{actionNameResponse}> (depends on what actionName is). Turn the
        # children of this into a {tagname, content} dict. XML unescaping
        # is carried out for us by elementree.
        action_response = tree.find(
            "{http://schemas.xmlsoap.org/soap/envelope/}Body")[0]
        return dict((i.tag, i.text or "") for i in action_response)
303948
def to_xml(self, xml_declaration=True):
        
        xml = ET.tostring(self.xml()).decode('utf-8')
        return '<?xml version="1.0" encoding="UTF-8"?>{}'.format(xml) if xml_declaration else xml
632890
def _parse_response_for_all_events(self, response):
    
    items = response.xpath(u'//m:FindItemResponseMessage/m:RootFolder/t:Items/t:CalendarItem', namespaces=soap_request.NAMESPACES)
    if not items:
      items = response.xpath(u'//m:GetItemResponseMessage/m:Items/t:CalendarItem', namespaces=soap_request.NAMESPACES)
    if items:
      self.count = len(items)
      log.debug(u'Found %s items' % self.count)

      for item in items:
        self._add_event(xml=soap_request.M.Items(deepcopy(item)))
    else:
      log.debug(u'No calendar items found with search parameters.')

    return self
496551
def AnalizarXml(self, xml=""):
        ""
        try:
            if not xml:
                xml = self.XmlResponse
            self.xml = SimpleXMLElement(xml)
            return True
        except Exception, e:
            self.Excepcion = u"%s" % (e)
            return False
280246
def xml2dict(xml, sanitize=True, prefix=None):
    
    from xml.etree import cElementTree as etree  # delayed import

    at = tx = ''
    if prefix:
        at, tx = prefix

    def astype(value):
        # return value as int, float, bool, or str
        for t in (int, float, asbool):
            try:
                return t(value)
            except Exception:
                pass
        return value

    def etree2dict(t):
        # adapted from https://stackoverflow.com/a/10077069/453463
        key = t.tag
        if sanitize:
            key = key.rsplit('}', 1)[-1]
        d = {key: {} if t.attrib else None}
        children = list(t)
        if children:
            dd = collections.defaultdict(list)
            for dc in map(etree2dict, children):
                for k, v in dc.items():
                    dd[k].append(astype(v))
            d = {key: {k: astype(v[0]) if len(v) == 1 else astype(v)
                       for k, v in dd.items()}}
        if t.attrib:
            d[key].update((at + k, astype(v)) for k, v in t.attrib.items())
        if t.text:
            text = t.text.strip()
            if children or t.attrib:
                if text:
                    d[key][tx + 'value'] = astype(text)
            else:
                d[key] = astype(text)
        return d

    return etree2dict(etree.fromstring(xml))
935443
def _parse_repo(self, xml):
        
        self.name = get_attrib(xml, "name", "repo")
        self.username = get_attrib(xml, "user", "repo")
        self.apikey = get_attrib(xml, "apikey", "repo")
        self.organization = get_attrib(xml, "organization")
        self.staging = get_attrib(xml, "staging", "repo")
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
1070119
def _extract_response_xml(self, domain, response):
        
        attributes = {}
        alexa_keys = {'POPULARITY': 'TEXT', 'REACH': 'RANK', 'RANK': 'DELTA'}
        try:
            xml_root = ET.fromstring(response._content)
            for xml_child in xml_root.findall('SD//'):
                if xml_child.tag in alexa_keys and \
                        alexa_keys[xml_child.tag] in xml_child.attrib:
                    attributes[xml_child.tag.lower(
                    )] = xml_child.attrib[alexa_keys[xml_child.tag]]
        except ParseError:
            # Skip ill-formatted XML and return no Alexa attributes
            pass
        attributes['domain'] = domain
        return {'attributes': attributes}
811802
def _parse_response(self, response):
        

        response_dict = {}
        for line in response.splitlines():
            key, value = response.split("=", 1)
            response_dict[key] = value
        return response_dict
1145557
def _xml_to_dict(xml):
    '''
    
    '''
    dicts = {}
    for item in xml:
        key = item.tag.lower()
        idx = 1
        while key in dicts:
            key += six.text_type(idx)
            idx += 1
        if item.text is None:
            dicts[key] = _xml_to_dict(item)
        else:
            dicts[key] = item.text

    return dicts
150849
def _send_request(self):
        
        
        # Generate the hash variable and parameters
        self._generate_hash()
        params = self._get_params()
        
        # Make the SOAP request
        try:
            resp = self._endpoint(**params)
            logger.debug(resp)
        except WebFault, e:
            logger.exception('An error occurred while making the SOAP request.')
            return None
        
        # Convert XML response into a dictionary
        self.response = XmlDictConfig(ElementTree.XML(smart_str(resp)))
        
        # Normalize dictionary values
        self.response = normalize_dictionary_values(self.response)
        
        # Log all non OK status codes
        if self.response['status']['errorCode'] != 'OK':
            logger.error(resp)
        
        return self.response
475533
def getXML(self):
        
        xml='<'+self._elementName+' '
        for key,value in list(self._attributes.items()):
            if value != None:
                xml+=key+'="'+self.quote_attrib(str(value))+'" '
        if  len(self._subElements)==0: #self._textContent==None and
            xml+=' />\n'
        else:
            xml+=' >\n'
            #if self._textContent==None:
            for subelement in self._subElements:
                s = subelement.getXML()
                if type(s) != str:
                    s = str(s)
                xml+=s
               # xml+=str(subelement.getXML())
            #else:
            #if self._textContent!=None:
            #    xml+=self._textContent
            xml+='</'+self._elementName+'>\n'
        #print xml
        return xml
329369
def raw_xml(self) -> _RawXML:
        
        if self._xml:
            return self._xml
        else:
            return etree.tostring(self.element, encoding='unicode').strip().encode(self.encoding)
1241928
def headers(self):
        
        action = self.method.soap.action
        result = {
            'Content-Type': 'text/xml; charset=utf-8',
            'SOAPAction': action
        }
        result.update(self.options.headers)
        log.debug('headers = %s', result)
        return result
1159474
def _serialize_xml(self, root):
        
        if hasattr(etree, 'tostringlist'):
            if six.PY3:
                xml_content_list = [
                    x.decode("utf-8") for x in etree.tostringlist(root)]
            else:
                xml_content_list = etree.tostringlist(root)

            xml = '\r\n'.join(xml_content_list) + '\r\n'
        else:
            if six.PY3:
                xml_content = etree.tostring(root).decode("utf-8")
            else:
                xml_content = etree.tostring(root)
            xml = xml_content + '\r\n'
        return xml
214426
def parse_soap_enveloped_saml_thingy(text, expected_tags):
    
    envelope = defusedxml.ElementTree.fromstring(text)

    # Make sure it's a SOAP message
    assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE

    assert len(envelope) >= 1
    body = None
    for part in envelope:
        if part.tag == '{%s}Body' % soapenv.NAMESPACE:
            assert len(part) == 1
            body = part
            break

    if body is None:
        return ""

    saml_part = body[0]
    if saml_part.tag in expected_tags:
        return ElementTree.tostring(saml_part, encoding="UTF-8")
    else:
        raise WrongMessageType("Was '%s' expected one of %s" % (saml_part.tag,
                                                                expected_tags))
766924
def parse_xml(self, xml):
        '''
            
        '''
        xmlutils = XmlUtils(xml)
        self.code_value = xmlutils.get_string_by_xpath('code-value')
        self.display_text = xmlutils.get_string_by_xpath('display-text')
        self.abbreviation_text = xmlutils.get_string_by_xpath('abbreviation-text')
        info_xml = xml.xpath('info-xml')
        if info_xml != []:
            self.info_xml = info_xml[0]