This method extracts valuable data from the XML structure
 of the soap response. It returns an array with extracted xml text nodes
 or nil, if the service provided no answer.
548107
def get_answer(doc, mod='')
      result = []
      # The path seems to be weird, because the namespaces change incrementally
      # in the output, so I don't want to treat it here.
      # A modifier needed because synonyms service provides duplicate values.
      XPath.each(doc, "//result/*/*#{mod}") do |el|
        warn(el.text) if $DEBUG
        result << el.text
      end

      result.any? ? result : nil
    end
573168
def to_xml
			result_string = String.new
			result_string << "<results>\n"
			@results.each do |result|
				result_string << "\t<vtresult>\n"
				RESULT_FIELDS.each{|field|
					result_string << "\t\t<#{field.to_s}>#{result[field]}</#{field.to_s}>\n" unless field == :permalink and result['permalink'].nil?
				}
				result_string << "\t</vtresult>\n"
			end if @results != nil
			result_string << "</results>\n"

			result_string
		end
292517
def class_instances_from_soap_enveloped_saml_thingies(text, modules):
    
    try:
        envelope = defusedxml.ElementTree.fromstring(text)
    except Exception as exc:
        raise XmlParseError("%s" % exc)

    assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
    assert len(envelope) >= 1
    env = {"header": [], "body": None}

    for part in envelope:
        if part.tag == '{%s}Body' % soapenv.NAMESPACE:
            assert len(part) == 1
            env["body"] = instanciate_class(part[0], modules)
        elif part.tag == "{%s}Header" % soapenv.NAMESPACE:
            for item in part:
                env["header"].append(instanciate_class(item, modules))

    return env
1023336
def _extract_links(self, selector, response_url, response_encoding, base_url):
        '''
        
        '''
        links = []
        # hacky way to get the underlying lxml parsed document
        for el, attr, attr_val in self._iter_links(selector.root):
            # pseudo lxml.html.HtmlElement.make_links_absolute(base_url)
            try:
                attr_val = urljoin(base_url, attr_val)
            except ValueError:
                continue # skipping bogus links
            else:
                url = self.process_attr(attr_val)
                if url is None:
                    continue
            # added 'ignore' to encoding errors
            url = to_native_str(url, encoding=response_encoding,
                                errors='ignore')
            # to fix relative links after process_value
            url = urljoin(response_url, url)
            link = Link(url, _collect_string_content(el) or u'',
                        nofollow=rel_has_nofollow(el.get('rel')))
            links.append(link)
        return self._deduplicate_if_needed(links)
1186521
def get_xml_str(self, data):
        

        responses = []
        for tag, value in data.items():
            elem = Element(tag)
            if isinstance(value, dict):
                for value in self.get_xml_str(value):
                    elem.append(value)
            elif isinstance(value, list):
                value = ', '.join([m for m in value])
                elem.text = value
            else:
                elem.text = value
            responses.append(elem)
        return responses
167138
def extract_paragraphs(xml_string):
    
    tree = etree.fromstring(xml_string.encode('utf-8'))

    paragraphs = []
    # In NLM xml, all plaintext is within <p> tags, and is the only thing
    # that can be contained in <p> tags. To handle to possibility of namespaces
    # uses regex to search for tags either of the form 'p' or '{<namespace>}p'
    for element in tree.iter():
        if isinstance(element.tag, basestring) and \
           re.search('(^|})[p|title]$', element.tag) and element.text:
            paragraph = ' '.join(element.itertext())
            paragraphs.append(paragraph)
    return paragraphs
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]
98210
def ParseHeaderElements(self, ofwhat):
        '''
        '''
        d = {}
        lenofwhat = len(ofwhat)
        c, crange = self.header_elements[:], range(len(self.header_elements))
        for i,what in [ (i, ofwhat[i]) for i in range(lenofwhat) ]:
            if isinstance(what, AnyElement): 
                raise EvaluateException, 'not supporting <any> as child of SOAP-ENC:Header'

            v = []
            occurs = 0
            namespaceURI,tagName = what.nspname,what.pname
            for j,c_elt in [ (j, c[j]) for j in crange if c[j] ]:
                prefix,name = SplitQName(c_elt.tagName)
                nsuri = _resolve_prefix(c_elt, prefix)
                if tagName == name and namespaceURI == nsuri:
                    pyobj = what.parse(c_elt, self)
                else:
                    continue
                v.append(pyobj)
                c[j] = None
            if what.minOccurs > len(v) > what.maxOccurs:
               raise EvaluateException, 'number of occurances(%d) doesnt fit constraints (%d,%s)'\
                   %(len(v),what.minOccurs,what.maxOccurs)
            if what.maxOccurs == 1:
                if len(v) == 0: v = None
                else: v = v[0]
            d[(what.nspname,what.pname)] = v
        return d
874885
def value_from_xml(node)
      if type.respond_to?(:new_from_xml)
        type.new_from_xml(node)
      elsif type.is_a?(Array)
        node.children.map do |sub_node|
          sub_field.value_from_xml(sub_node)
        end
      elsif type == Boolean
        node.text == "true"
      elsif type == Integer
        node.text.to_i unless node.text.empty?
      elsif type == Time
        Time.xmlschema(node.text) unless node.text.empty?
      else
        node.text
      end
    end
897040
def parse_xml(response)
      data = Nokogiri::XML(response) do |config| config.strict.noblanks end
      fail OptaSD::Error.new(xml_error_to_hast(data)), ErrorMessage.get_message(data.children.first.content.to_i) if data.css('errorCode').first.present?
      data
    end
930295
def parse(node)
      node.attributes.each do |key, value|
        case key
        when 'count'
          @count = value.value.to_i
        end
      end

      node.xpath('*').each do |node_child|
        case node_child.name
        when 'xf'
          @xf_array << Xf.new(parent: self).parse(node_child)
        end
      end
      self
    end
1364407
def decode(data):
    
    dom = None
    try:
        dom = dhtmlparser.parseString(data)
    except Exception, e:
        raise MetaParsingException("Can't parse your XML data: %s" % e.message)

    root = dom.find("root")

    # check whether there is <root>s
    if not root:
        raise MetaParsingException("All elements have to be inside <root>.")

    # and make sure, that there is not too many <root>s
    if len(root) > 1:
        raise MetaParsingException("Too many <root> elements in your XML!")

    items = root[0].find("item")

    # check for items
    if not items:
        raise MetaParsingException("There are no <items> in your XML <root>!")

    decoded = []
    for item in items:
        if "key" not in item.params:
            raise MetaParsingException(
                "There is no 'key' parameter in %s." % str(item)
            )

        decoded.append([
            item.params["key"],
            item.getContent().strip()
        ])

    decoded = validator.check_structure(decoded)

    return decoded
825416
private String parseXmlElement(Element element) {
        if(element.getFirstChild() instanceof Text) {
            Text text = (Text) element.getFirstChild();
            return text.getData();
        }
       
        return toXml(element);
    }
1035797
def _extract(self, raw: str, station: str = None) -> str:
        
        resp = parsexml(raw)
        try:
            report = resp['response']['body']['items']['item'][self.rtype.lower() + 'Msg']
        except KeyError:
            raise self.make_err(raw)
        # Replace line breaks
        report = report.replace('\n', '')
        # Remove excess leading and trailing data
        for item in (self.rtype.upper(), 'SPECI'):
            if report.startswith(item + ' '):
                report = report[len(item) + 1:]
        report = report.rstrip('=')
        # Make every element single-spaced and stripped
        return ' '.join(report.split())
670629
def analyze_xml(xml):
    

    f = StringIO(xml)

    try:
        xml = packtools.XMLValidator.parse(f, sps_version='sps-1.4')
    except packtools.exceptions.PacktoolsError as e:
        logger.exception(e)
        summary = {}
        summary['dtd_is_valid'] = False
        summary['sps_is_valid'] = False
        summary['is_valid'] = False
        summary['parsing_error'] = True
        summary['dtd_errors'] = []
        summary['sps_errors'] = []
        return summary
    except XMLSyntaxError as e:
        logger.exception(e)
        summary = {}
        summary['dtd_is_valid'] = False
        summary['sps_is_valid'] = False
        summary['is_valid'] = False
        summary['parsing_error'] = True
        summary['dtd_errors'] = [e.message]
        summary['sps_errors'] = []
        return summary
    else:
        summary = summarize(xml)

        return summary
318481
function extractPayload(content) {
        var payload = {};

        if (content[0] !== "<") {
            // text
            payload.nodeType = 3;
            payload.nodeValue = content;
        } else if (content.substr(0, 4) === "<!--") {
            // comment
            payload.nodeType = 8;
            payload.nodeValue = content.substr(4, content.length - 7);
        } else if (content[1] === "!") {
            // doctype
            payload.nodeType = 10;
        } else {
            // regular element
            payload.nodeType = 1;
            payload.nodeName = /^<([^>\s]+)/.exec(content)[1].toUpperCase();
            payload.attributes = _extractAttributes(content);

            // closing node (/ at the beginning)
            if (payload.nodeName[0] === "/") {
                payload.nodeName = payload.nodeName.substr(1);
                payload.closing = true;
            }

            // closed node (/ at the end)
            if (content[content.length - 2] === "/") {
                payload.closed = true;
            }

            // Special handling for script/style tag since we've already collected
            // everything up to the end tag.
            if (payload.nodeName === "SCRIPT" || payload.nodeName === "STYLE") {
                payload.closed = true;
            }
        }
        return payload;
    }
1106766
function extractServices(search, services) {
  if (!search) { return; }

  if (Array.isArray(search)) {
    // We got passed an array of nodes, process each one individualy
    search.forEach(function (item) {
      extractServices(item, services);
    });
  }

  else if (search.dir) {
    // We are a directory, recurse with the nodes
    extractServices(search.nodes, services);
  }

  else if (search.node) {
    // We are at the root of the search, recurse with the node's result
    extractServices(search.node, services);
  }

  else if (search.value) {
    // We are finaly at a leaf, extract the service info
    services[search.key] = search.value;
  }

  return;
}