Given an XML document (string) returned from metadata_query(),
    parse the response into a list of track info dicts. May raise an
    APIError if the lookup fails.
772754
def parse_metadata(xml):
    
    try:
        root = etree.fromstring(xml)
    except (ExpatError, etree.ParseError):
        # The Last.fm API occasionally generates malformed XML when its
        # includes an illegal character (UTF8-legal but prohibited by
        # the XML standard).
        raise CommunicationError('malformed XML response')
    
    status = root.attrib['status']
    if status == 'failed':
        error = root.find('error')
        raise APIError(int(error.attrib['code']), error.text)
    
    out = []
    for track in root.find('tracks').findall('track'):
        out.append({
            'rank': float(track.attrib['rank']),
            'artist': track.find('artist').find('name').text,
            'artist_mbid': track.find('artist').find('mbid').text,
            'title': track.find('name').text,
            'track_mbid': track.find('mbid').text,
        })
    return out
1084806
def parse_solr_response(response)
      rows = []

      response.docs.each do |doc|
        id = doc['id'].split('/').last
        isShownAt_id = doc['isShownAt_id'].respond_to?(:first) ?
          doc['isShownAt_id'].first : '__MISSING__'

        if doc[field].present?
          doc[field].each do |value|
            rows << { :id => id,
                      field.to_sym => value,
                      :isShownAt_id => isShownAt_id }
          end
        else
          rows << { :id => id,
                    field.to_sym => '__MISSING__',
                    :isShownAt_id => isShownAt_id }
        end
      end

      rows
    end
1312113
def read_xml(self):
        

        with reading_ancillary_files(self):
            root = super(ImpactLayerMetadata, self).read_xml()
            if root is not None:
                self._read_provenance_from_xml(root)
        return root
944357
def _parse_search_results_html(self, doc):
        
        subgroups = []
        soup = bs4.BeautifulSoup(doc, 'lxml')
        ele_divs = soup.select('div.item.prel')
        if not ele_divs:
            return subgroups
        for item in ele_divs:
            ele_a = item.select('p.tt > a')
            if not ele_a:
                continue
            link = ele_a[0].get('href')
            title = ele_a[0].get_text().strip()
            subgroups.append({
                'title': title,
                'link': link,
            })
        return subgroups
924665
def parse_pandoc(self, attrs):
        """"""
        id = attrs[0]
        classes = attrs[1]
        kvs = OrderedDict(attrs[2])

        return id, classes, kvs
967181
def parse_xml(self, key_xml):
        '''
            
        '''
        xmlutils = XmlUtils(key_xml)
        self.name = xmlutils.get_string_by_xpath('name')
        self.family = xmlutils.get_string_by_xpath('family')
        self.version = xmlutils.get_string_by_xpath('version')
        self.description = xmlutils.get_string_by_xpath('description')

        self.language = xmlutils.get_lang()
870322
def parse_meta(content, meta_name, source_descr, content_attr_name="content"):
    
    dom = dhtmlparser.parseString(content)

    meta_tags = dom.find(
        "meta",
        fn=lambda x: x.params.get("name", "").lower() == meta_name.lower()
    )

    return [
        SourceString(tag.params[content_attr_name], source_descr)
        for tag in meta_tags
        if content_attr_name in tag.params
    ]
371022
def _parse_request(self, xml):
        
        for node in xml.xpath(".//ti:groupname", namespaces=XPATH_NAMESPACES):
            lang = node.get("xml:lang") or CtsText.DEFAULT_LANG
            self.metadata.add(RDF_NAMESPACES.CTS.groupname, lang=lang, value=node.text)
            self.set_creator(node.text, lang)

        for node in xml.xpath(".//ti:title", namespaces=XPATH_NAMESPACES):
            lang = node.get("xml:lang") or CtsText.DEFAULT_LANG
            self.metadata.add(RDF_NAMESPACES.CTS.title, lang=lang, value=node.text)
            self.set_title(node.text, lang)

        for node in xml.xpath(".//ti:label", namespaces=XPATH_NAMESPACES):
            lang = node.get("xml:lang") or CtsText.DEFAULT_LANG
            self.metadata.add(RDF_NAMESPACES.CTS.label, lang=lang, value=node.text)
            self.set_subject(node.text, lang)

        for node in xml.xpath(".//ti:description", namespaces=XPATH_NAMESPACES):
            lang = node.get("xml:lang") or CtsText.DEFAULT_LANG
            self.metadata.add(RDF_NAMESPACES.CTS.description, lang=lang, value=node.text)
            self.set_description(node.text, lang)

        # Need to code that p
        if not self.citation.is_set() and xml.xpath("//ti:citation", namespaces=XPATH_NAMESPACES):
            self.citation = CtsCollection.XmlCtsCitation.ingest(
                xml,
                xpath=".//ti:citation[not(ancestor::ti:citation)]"
            )
1087831
def _get_doc_by_raw_offset(self, doc_id):
        
        bounds = self._get_meta()[str(doc_id)].bounds
        return xml_utils.load_chunk(self.filename, bounds)
1056265
def parse_owl_xml(url):
    
    res = download(url)
    owl = OWLParser(content=res.content)
    return owl
1094171
def parse_fast(xmlfile, element_name, attrnames, warn=False, optional=False):
    
    prefixedAttrnames = [_prefix_keyword(a, warn) for a in attrnames]
    if optional:
        pattern = ''.join(['<%s' % element_name] +
                          ['(\\s+%s="(?P<%s>[^"]*?)")?' % a for a in zip(attrnames, prefixedAttrnames)])
    else:
        pattern = '.*'.join(['<%s' % element_name] +
                            ['%s="([^"]*)"' % attr for attr in attrnames])
    Record = namedtuple(element_name, prefixedAttrnames)
    reprog = re.compile(pattern)
    for line in open(xmlfile):
        m = reprog.search(line)
        if m:
            if optional:
                yield Record(**m.groupdict())
            else:
                yield Record(*m.groups())
1250602
def parse(self, response, metadata_type):
        
        xml = xmltodict.parse(response.text)
        self.analyze_reply_code(xml_response_dict=xml)
        base = xml.get('RETS', {}).get(metadata_type, {})
        attributes = self.get_attributes(base)

        parsed = []
        if base.get('System') or base.get('SYSTEM'):
            system_obj = {}

            if base.get('SYSTEM', {}).get('@SystemDescription'):
                system_obj['system_id'] = str(base['SYSTEM']['@SystemID'])

            if base.get('SYSTEM', {}).get('@SystemDescription'):
                system_obj['system_description'] = str(base['SYSTEM']['@SystemDescription'])

            if base.get('SYSTEM', {}).get('@TimeZoneOffset'):
                system_obj['timezone_offset'] = str(base['SYSTEM']['@TimeZoneOffset'])

            if base.get('SYSTEM', {}).get('Comments'):
                system_obj['comments'] = base['SYSTEM']['Comments']

            if base.get('@Version'):
                system_obj['version'] = base['@Version']

            parsed.append(system_obj)

        elif 'DATA' in base:
            if not isinstance(base['DATA'], list):  # xmltodict could take single entry XML lists and turn them into str
                base['DATA'] = [base['DATA']]

            for data in base['DATA']:
                data_dict = self.data_columns_to_dict(columns_string=base.get('COLUMNS', ''), dict_string=data)
                data_dict.update(attributes)
                parsed.append(data_dict)

        return parsed
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
964531
def parse_metadata(section):
  """"""
  metadata = {}
  metadata_lines = section.split('\n')
  for line in metadata_lines:
    colon_index = line.find(':')
    if colon_index != -1:
      key = line[:colon_index].strip()
      val = line[colon_index + 1:].strip()
      metadata[key] = val

  return metadata
480752
def _parse_xml(self):
        
        import xml.etree.ElementTree as ET
        from os import path
        #This dict has the keys of XML tags that are required in order for the
        #CI server to run the repo. When each one is parsed, we change its value
        #to True and then check that they are all true at the end.
        required = {"testing": False, "wiki": False}
        #Make sure the file exists and then import it as XML and read the values out.
        if path.isfile(self.filepath):
            tree = ET.parse(self.filepath)
            vms("Parsing XML tree from {}.".format(self.filepath), 2)
            root = tree.getroot()
            if root.tag != "cirepo":
                raise ValueError("The root tag in a continuous integration settings XML "
                                 "file should be a <cirepo> tag.")

            self._parse_repo(root)
            for child in root:
                if child.tag == "cron":
                    if self.server is not None:
                        self.server.cron.settings[self.name] = CronSettings(child)
                if child.tag == "testing":
                    self.testing = TestingSettings(child)
                if child.tag == "static":
                    self.static = StaticSettings(child)
                if child.tag == "wiki":
                    self.wiki["user"] = get_attrib(child, "user", "wiki")
                    self.wiki["password"] = get_attrib(child, "password", "wiki")
                    self.wiki["basepage"] = get_attrib(child, "basepage", "wiki")
                if child.tag in required:
                    required[child.tag] = True

            if not all(required.values()):
                tags = ', '.join(["<{}>".format(t) for t in required])
                raise ValueError("{} are required tags in the repo's XML settings file.".format(tags))
1106497
def parsemetadata(ebook):
	
	result = dict.fromkeys(META_FIELDS)
	# get etext no
	about = ebook.get('{%(rdf)s}about' % NS)
	result['id'] = int(os.path.basename(about))
	# author
	creator = ebook.find('.//{%(dc)s}creator' % NS)
	if creator is not None:
		name = creator.find('.//{%(pg)s}name' % NS)
		if name is not None:
			result['author'] = safeunicode(name.text, encoding='utf-8')
		birth = creator.find('.//{%(pg)s}birthdate' % NS)
		if birth is not None:
			result['authoryearofbirth'] = int(birth.text)
		death = creator.find('.//{%(pg)s}deathdate' % NS)
		if death is not None:
			result['authoryearofdeath'] = int(death.text)
	# title
	title = ebook.find('.//{%(dc)s}title' % NS)
	if title is not None:
		result['title'] = fixsubtitles(
				safeunicode(title.text, encoding='utf-8'))
	# subject lists
	result['subjects'], result['LCC'] = set(), set()
	for subject in ebook.findall('.//{%(dc)s}subject' % NS):
		res = subject.find('.//{%(dcam)s}memberOf' % NS)
		if res is None:
			continue
		res = res.get('{%(rdf)s}resource' % NS)
		value = subject.find('.//{%(rdf)s}value' % NS).text
		if res == ('%(dc)sLCSH' % NS):
			result['subjects'].add(value)
		elif res == ('%(dc)sLCC' % NS):
			result['LCC'].add(value)
	# formats
	result['formats'] = {file.find('{%(dc)s}format//{%(rdf)s}value' % NS).text:
			file.get('{%(rdf)s}about' % NS)
			for file in ebook.findall('.//{%(pg)s}file' % NS)}
	# type
	booktype = ebook.find('.//{%(dc)s}type//{%(rdf)s}value' % NS)
	if booktype is not None:
		result['type'] = booktype.text
	# languages
	lang = ebook.findall('.//{%(dc)s}language//{%(rdf)s}value' % NS)
	result['language'] = [a.text for a in lang] or None
	# download count
	downloads = ebook.find('.//{%(pg)s}downloads' % NS)
	if downloads is not None:
		result['downloads'] = int(downloads.text)
	return result
692646
def parse_endnotes(document, xmlcontent):
    

    endnotes = etree.fromstring(xmlcontent)
    document.endnotes = {}

    for note in endnotes.xpath('.//w:endnote', namespaces=NAMESPACES):
        paragraphs = [parse_paragraph(document, para) for para in note.xpath('.//w:p', namespaces=NAMESPACES)]

        document.endnotes[note.attrib[_name('{{{w}}}id')]] = paragraphs