构建带翻页的列表
    
    :param results: 已获取的数据列表
    :param xml: 原始页面xml
    :return: {'results': list, 'count': int, 'next_start': int|None}
            如果count与results长度不同，则有更多
            如果next_start不为None，则可以到下一页
553431
def build_list_result(results, xml):
    
    xml_count = xml.xpath('//div[@class="paginator"]/span[@class="count"]/text()')
    xml_next = xml.xpath('//div[@class="paginator"]/span[@class="next"]/a/@href')
    count = int(re.search(r'\d+', xml_count[0]).group()) if xml_count else len(results)
    next_start = int(re.search(r'start=(\d+)', xml_next[0]).groups()[0]) if xml_next else None
    return {'results': results, 'count': count, 'next_start': next_start}
926160
def find_node(results, node_name)
      document = ::Nokogiri::XML(results.body)
      document.remove_namespaces!
      document.xpath("//#{node_name}").first
    end
835508
async def parseResults(self, api_data):
    
    results = []

    # parse HTML and get results
    parser = lxml.etree.HTMLParser()
    html = lxml.etree.XML(api_data.decode("latin-1"), parser)

    for rank, result in enumerate(__class__.RESULTS_SELECTOR(html), 1):
      # extract url
      metadata_div = result.find("div")
      metadata_json = lxml.etree.tostring(metadata_div, encoding="unicode", method="text")
      metadata_json = json.loads(metadata_json)
      google_url = result.find("a").get("href")
      if google_url is not None:
        query = urllib.parse.urlsplit(google_url).query
      else:
        query = None
      if not query:
        img_url = metadata_json["ou"]
      else:
        query = urllib.parse.parse_qs(query)
        img_url = query["imgurl"][0]
      # extract format
      check_metadata = CoverImageMetadata.NONE
      format = metadata_json["ity"].lower()
      try:
        format = SUPPORTED_IMG_FORMATS[format]
      except KeyError:
        # format could not be identified or is unknown
        format = None
        check_metadata = CoverImageMetadata.FORMAT
      # extract size
      if not query:
        size = metadata_json["ow"], metadata_json["oh"]
      else:
        size = tuple(map(int, (query["w"][0], query["h"][0])))
      # extract thumbnail url
      thumbnail_url = metadata_json["tu"]
      # result
      results.append(GoogleImagesCoverSourceResult(img_url,
                                                   size,
                                                   format,
                                                   thumbnail_url=thumbnail_url,
                                                   source=self,
                                                   rank=rank,
                                                   check_metadata=check_metadata))

    return results
871880
def from_xml(cls, xml):
        
        s = parse_string(xml)
        return Sentence(s.split("\n")[0], token=s.tags, language=s.language)
557486
def parse(self,xml):
    
    if not self.xmlparser:
      raise LIGOLwParseError, "pyRXP parser not initialized"
    if not self.lwtparser:
      raise LIGOLwParseError, "LIGO_LW tuple parser not initialized"
    xml = "".join([x.strip() for x in xml.split('\n')])
    ligolwtup = self.xmlparser(xml)
    if self.curs:
      self.lwtparser.unique = UniqueIds(self.curs)
    self.table = self.lwtparser.parsetuple(ligolwtup)
472444
def parse_trips(self, xml, requested_time):
        
        obj = xmltodict.parse(xml)
        trips = []

        if 'error' in obj:
            print('Error in trips: ' + obj['error']['message'])
            return None

        try:
            for trip in obj['ReisMogelijkheden']['ReisMogelijkheid']:
                newtrip = Trip(trip, requested_time)
                trips.append(newtrip)
        except TypeError:
            # If no options are found, obj['ReisMogelijkheden'] is None
            return None

        return trips
1129009
def toxml(self):
        
        chxmlstr = ''

        for with_ in self.withs:
            chxmlstr += with_.toxml()

        for event_connection in self.event_connections:
            chxmlstr += event_connection.toxml()

        for child_instance in self.child_instances:
            chxmlstr += child_instance.toxml()

        for multi_instantiate in self.multi_instantiates:
            chxmlstr += multi_instantiate.toxml()

        for for_each in self.for_eachs:
            chxmlstr += for_each.toxml()

        if chxmlstr:
            xmlstr = '<Structure>' + chxmlstr + '</Structure>'
        else:
            xmlstr = ''

        return xmlstr
367355
def _process_layperson_results(self, results):
        

        payload = {
            'results': []
        }

        for doc in results.docs:
            hl = self._process_highlight(results, doc)
            highlight = {
                'id': doc['id'],
                'highlight': hl.highlight,
                'label': doc['label'],
                'matched_synonym': hl.match
            }
            payload['results'].append(highlight)

        logging.debug('Docs: {}'.format(len(results.docs)))

        return payload
758019
private String getListResultString(List result) {
        StringBuilder sb = new StringBuilder();
        Iterator i = result.iterator();
        if (!i.hasNext()) {
            return "[]";
        }
        sb.append('[');
        for (;;) {
            Object e = i.next();
            // 注意: 修改为getResultString(e)进行递归处理
            sb.append(e == this ? "(this Collection)" : getResultString(e));
            if (!i.hasNext()) {
                return sb.append(']').toString();
            }
            sb.append(", ");
        }
    }
1083938
def find_tags_from_xml(
        self, xml_name, tag_name, **attribute_filter
    ):
        
        xml = self.xml[xml_name]
        if xml is None:
            return []
        if xml.tag == tag_name:
            if self.is_tag_matched(
                xml.tag, **attribute_filter
            ):
                return [xml]
            return []
        tags = xml.findall(".//" + tag_name)
        return [
            tag for tag in tags if self.is_tag_matched(
                tag, **attribute_filter
            )
        ]
638093
public static Document getResultSetAsXML(ResultSet rs, String tableName, String keyName) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        Element results = doc.createElement("Results");
        doc.appendChild(results);

        ResultSetMetaData rsmd = rs.getMetaData();
        // add the name of the table
        Element tableNameElement = doc.createElement("table");
        tableNameElement.setAttribute("name", tableName);
        tableNameElement.setAttribute("key", keyName);
        results.appendChild(tableNameElement);

        int colCount = rsmd.getColumnCount();

        while (rs.next()) {
            Element row = doc.createElement("Row");
            tableNameElement.appendChild(row);
            for (int i = 1; i <= colCount; i++) {
                String columnName = rsmd.getColumnName(i);
                Object value = rs.getObject(i);
                // If the value is null, don't put it in the XML Document
                if (value != null) {
                    String colType = rsmd.getColumnTypeName(i);
                    Element node = doc.createElement(columnName);
                    if (colType.equals("bytea")) {
                        String byteaStr = "";
                        byte[] imgBytes = rs.getBytes(i);
                        for (int byteIndex = 0; byteIndex < imgBytes.length; byteIndex++) {
                            if (byteIndex != 0) {
                                byteaStr = byteaStr + ";" + Byte.toString(imgBytes[byteIndex]);
                            } else {
                                byteaStr = Byte.toString(imgBytes[byteIndex]);
                            }
                        }
                        node.appendChild(doc.createTextNode(byteaStr));
                    } else {
                        node.appendChild(doc.createTextNode(value.toString()));
                    }
                    row.appendChild(node);
                }
            }
        }
        return doc;
    }
715901
def _parse_response(self, results):
        

        dict_response = results.get("response")
        result_obj = SolrResults()
        result_obj.query_time = results.get("responseHeader").get("QTime", None)
        result_obj.results_count = dict_response.get("numFound", 0)
        result_obj.start_index = dict_response.get("start", 0)

        for doc in dict_response.get("docs", []):
            result_obj.documents.append(doc)

        # Process facets
        if "facet_counts" in results:
            facet_types = ["facet_fields", "facet_dates", "facet_ranges", "facet_queries"]
            for type in facet_types:
                assert type in results.get("facet_counts")
                items = results.get("facet_counts").get(type)
                for field, values in items.items():
                    result_obj.facets[field] = []

                    # Range facets have results in "counts" subkey and "between/after" on top level. Flatten this.
                    if type == "facet_ranges":
                        if not "counts" in values:
                            continue

                        for facet, value in values["counts"].items():
                            result_obj.facets[field].append((facet, value))

                        if "before" in values:
                            result_obj.facets[field].append(("before", values["before"]))

                        if "after" in values:
                            result_obj.facets[field].append(("after", values["after"]))
                    else:
                        for facet, value in values.items():
                            # Date facets have metadata fields between the results, skip the params, keep "before" and "after" fields for other
                            if type == "facet_dates" and \
                            (facet == "gap" or facet == "between" or facet == "start" or facet == "end"):
                                continue
                            result_obj.facets[field].append((facet, value))

        # Process highlights
        if "highlighting" in results:
            for key, value in results.get("highlighting").items():
                result_obj.highlights[key] = value

        return result_obj
994653
def append(self, resultFile, resultElem, all_columns=False):
        
        self._xml_results += [(result, resultFile) for result in _get_run_tags_from_xml(resultElem)]
        for attrib, values in RunSetResult._extract_attributes_from_result(resultFile, resultElem).items():
            self.attributes[attrib].extend(values)

        if not self.columns:
            self.columns = RunSetResult._extract_existing_columns_from_result(resultFile, resultElem, all_columns)
569996
private String getNext() {
    StringBuilder result = new StringBuilder();
    try {
      XMLUtils.XMLTag tag;
      do {
        // String text =
        XMLUtils.readUntilTag(inputReader);
        // there may or may not be text before the next tag, but we discard it
        //        System.out.println("outside text: " + text );
        tag = XMLUtils.readAndParseTag(inputReader);
        //        System.out.println("outside tag: " + tag);
        if (tag == null) {
          return null; // couldn't find any more tags, so no more elements
        }
      } while (!tagNamePattern.matcher(tag.name).matches() ||
               tag.isEndTag || tag.isSingleTag);
      if (keepDelimitingTags) {
        result.append(tag.toString());
      }
      int depth = 1;
      while (true) {
        String text = XMLUtils.readUntilTag(inputReader);
        if (text != null) {
          // if the text isn't null, we append it
          //        System.out.println("inside text: " + text );
          result.append(text);
        }
        String tagString = XMLUtils.readTag(inputReader);
        tag = XMLUtils.parseTag(tagString);
        if (tag == null) {
          return null; // unexpected end of this element, so no more elements
        }
        if (tagNamePattern.matcher(tag.name).matches() && tag.isEndTag) {
          if ((countDepth && depth == 1) || !countDepth) {
            if (keepDelimitingTags) {
              result.append(tagString);
            }
            // this is our end tag so we stop
            break;
          } else {
            --depth;
            if (keepInternalTags) {
              result.append(tagString);
            }
          }
        } else if (tagNamePattern.matcher(tag.name).matches() && !tag.isEndTag &&
                   !tag.isSingleTag && countDepth) {
          ++depth;
          if (keepInternalTags) {
            result.append(tagString);
          }
        } else {
          // not our end tag, so we optionally append it and keep going
          if (keepInternalTags) {
            result.append(tagString);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result.toString();
  }
211940
function(result) {
    var oResult = {},
        schema = this.responseSchema;
        
    try {
        // Loop through each data field in each result using the schema
        for(var m = schema.fields.length-1; m >= 0 ; m--) {
            var field = schema.fields[m];
            var key = (lang.isValue(field.key)) ? field.key : field;
            var data = null;

            if(this.useXPath) {
                data = YAHOO.util.DataSource._getLocationValue(field, result);
            }
            else {
                // Values may be held in an attribute...
                var xmlAttr = result.attributes.getNamedItem(key);
                if(xmlAttr) {
                    data = xmlAttr.value;
                }
                // ...or in a node
                else {
                    var xmlNode = result.getElementsByTagName(key);
                    if(xmlNode && xmlNode.item(0)) {
                        var item = xmlNode.item(0);
                        // For IE, then DOM...
                        data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
                        // ...then fallback, but check for multiple child nodes
                        if(!data) {
                            var datapieces = [];
                            for(var j=0, len=item.childNodes.length; j<len; j++) {
                                if(item.childNodes[j].nodeValue) {
                                    datapieces[datapieces.length] = item.childNodes[j].nodeValue;
                                }
                            }
                            if(datapieces.length > 0) {
                                data = datapieces.join("");
                            }
                        }
                    }
                }
            }
            
            
            // Safety net
            if(data === null) {
                   data = "";
            }
            // Backward compatibility
            if(!field.parser && field.converter) {
                field.parser = field.converter;
                YAHOO.log("The field property converter has been deprecated" +
                        " in favor of parser", "warn", this.toString());
            }
            var parser = (typeof field.parser === 'function') ?
                field.parser :
                DS.Parser[field.parser+''];
            if(parser) {
                data = parser.call(this, data);
            }
            // Safety measure
            if(data === undefined) {
                data = null;
            }
            oResult[key] = data;
        }
    }
    catch(e) {
        YAHOO.log("Error while parsing XML result: " + e.message);
    }

    return oResult;
}
718722
def extract_runs_from_xml(self, sourcefilesTagList, global_required_files_pattern):
        '''
        
        '''
        base_dir = self.benchmark.base_dir
        # runs are structured as sourcefile sets, one set represents one sourcefiles tag
        blocks = []

        for index, sourcefilesTag in enumerate(sourcefilesTagList):
            sourcefileSetName = sourcefilesTag.get("name")
            matchName = sourcefileSetName or str(index)
            if self.benchmark.config.selected_sourcefile_sets \
                and not any(util.wildcard_match(matchName, sourcefile_set) for sourcefile_set in self.benchmark.config.selected_sourcefile_sets):
                    continue

            required_files_pattern = global_required_files_pattern.union(
                set(tag.text for tag in sourcefilesTag.findall('requiredfiles')))

            # get lists of filenames
            task_def_files = self.get_task_def_files_from_xml(sourcefilesTag, base_dir)

            # get file-specific options for filenames
            fileOptions = util.get_list_from_xml(sourcefilesTag)
            propertyfile = util.text_or_none(util.get_single_child_from_xml(sourcefilesTag, PROPERTY_TAG))

            # some runs need more than one sourcefile,
            # the first sourcefile is a normal 'include'-file, we use its name as identifier
            # for logfile and result-category all other files are 'append'ed.
            appendFileTags = sourcefilesTag.findall("append")

            currentRuns = []
            for identifier in task_def_files:
                if identifier.endswith('.yml'):
                    if appendFileTags:
                        raise BenchExecException(
                            "Cannot combine <append> and task-definition files in the same <tasks> tag.")
                    run = self.create_run_from_task_definition(
                        identifier, fileOptions, propertyfile, required_files_pattern)
                else:
                    run = self.create_run_for_input_file(
                        identifier, fileOptions, propertyfile, required_files_pattern, appendFileTags)
                if run:
                    currentRuns.append(run)

            # add runs for cases without source files
            for run in sourcefilesTag.findall("withoutfile"):
                currentRuns.append(Run(run.text, [], fileOptions, self, propertyfile, required_files_pattern))

            blocks.append(SourcefileSet(sourcefileSetName, index, currentRuns))

        if self.benchmark.config.selected_sourcefile_sets:
            for selected in self.benchmark.config.selected_sourcefile_sets:
                if not any(util.wildcard_match(sourcefile_set.real_name, selected) for sourcefile_set in blocks):
                    logging.warning(
                        'The selected tasks "%s" are not present in the input file, '
                        'skipping them.',
                        selected)
        return blocks
1320229
def get_scan_results_xml(self, scan_id, pop_res):
        
        results = Element('results')
        for result in self.scan_collection.results_iterator(scan_id, pop_res):
            results.append(get_result_xml(result))

        logger.info('Returning %d results', len(results))
        return results