Parse an XML object for structured metadata

    :param obj: Object whose metadata are parsed
    :param xml: XML that needs to be parsed
970788
def _parse_structured_metadata(obj, xml):
    
    for metadata in xml.xpath("cpt:structured-metadata/*", namespaces=XPATH_NAMESPACES):
        tag = metadata.tag
        if "{" in tag:
            ns, tag = tuple(tag.split("}"))
            tag = URIRef(ns[1:]+tag)
            s_m = str(metadata)
            if s_m.startswith("urn:") or s_m.startswith("http:") or s_m.startswith("https:") or s_m.startswith("hdl:"):
                obj.metadata.add(
                    tag,
                    URIRef(metadata)
                )
            elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata.attrib:
                obj.metadata.add(
                    tag,
                    s_m,
                    lang=metadata.attrib['{http://www.w3.org/XML/1998/namespace}lang']
                )
            else:
                if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata.attrib:
                    datatype = metadata.attrib["{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype"]
                    if not datatype.startswith("http") and ":" in datatype:
                        datatype = expand_namespace(metadata.nsmap, datatype)
                    obj.metadata.add(tag, Literal(s_m, datatype=URIRef(datatype)))
                elif isinstance(metadata, IntElement):
                    obj.metadata.add(tag, Literal(int(metadata), datatype=XSD.integer))
                elif isinstance(metadata, FloatElement):
                    obj.metadata.add(tag, Literal(float(metadata), datatype=XSD.float))
                else:
                    obj.metadata.add(tag, s_m)
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]
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)
270358
def _parse_dict(element, definition):
    
    sub_dict = {}

    for name, subdef in viewitems(definition):
        (name, required) = _parse_name(name)

        sub_dict[name] = xml_to_json(element, subdef, required)

    return sub_dict
402033
def parse_xml(self, xml):
        '''
            
        '''
        xmlutils = XmlUtils(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')
        for item in xml.xpath('code-item'):
            self.code_item.append(VocabularyCodeItem(item))
        self.is_vocab_truncated = xmlutils.get_bool_by_xpath('is-vocab-truncated')
        self.language = xmlutils.get_lang()
1016370
function XmlDocument(xml) {
  xml && (xml = xml.toString().trim());

  if (!xml)
    throw new Error("No XML to parse!");

  // Expose the parser to the other delegates while the parser is running
  this.parser = sax.parser(true); // strict
  addParserEvents(this.parser);

  // We'll use the file-scoped "delegates" var to remember what elements we're currently
  // parsing; they will push and pop off the stack as we get deeper into the XML hierarchy.
  // It's safe to use a global because JS is single-threaded.
  delegates = [this];
  
  this.parser.write(xml);

  // Remove the parser as it is no longer needed and should not be exposed to clients
  delete this.parser;
}
1195208
def _parse_xml(child, parser):
    """"""
    name, modifiers, dtype, kind = _parse_common(child)

    #Handle the symbol modification according to the isense settings.
    name = _isense_builtin_symbol(name)

    if child.tag == "subroutine":
        parent = Subroutine(name, modifiers, None)
    elif child.tag == "function":
        parent = Function(name, modifiers, dtype, kind, None)

    if parent is not None:
        for kid in child:
            if kid.tag == "parameter":
                _parse_parameter(kid, parser, parent)
            elif kid.tag == "summary":
                _parse_summary(kid, parser, parent)
            elif kid.tag == "usage":
                _parse_usage(kid, parser, parent)

    return parent
306231
def _ParsePropertiesXMLFile(self, xml_data):
    
    xml_root = ElementTree.fromstring(xml_data)

    properties = {}
    for xml_element in xml_root.iter():
      if not xml_element.text:
        continue

      # The property name is formatted as: {URL}name
      # For example: {http://purl.org/dc/terms/}modified
      _, _, name = xml_element.tag.partition('}')

      # Do not including the 'lpstr' attribute because it is very verbose.
      if name == 'lpstr':
        continue

      property_name = self._PROPERTY_NAMES.get(name, None)
      if not property_name:
        property_name = self._FormatPropertyName(name)

      properties[property_name] = xml_element.text

    return properties
1357521
def parse_xml(self, node):
        
        self._set_properties(node)
        self.name = node.get('name', None)
        self.opacity = node.get('opacity', self.opacity)
        self.visible = node.get('visible', self.visible)
        image_node = node.find('image')
        self.source = image_node.get('source', None)
        self.trans = image_node.get('trans', None)
        return self
871970
def _parse_xml(self, xml):
        """"""
        from re import split
        vms("Parsing <cron> XML child tag.", 2)
        self.frequency = get_attrib(xml, "frequency", default=5, cast=int)
        self.emails = split(",\s*", get_attrib(xml, "emails", default=""))
        self.notify = split(",\s*", get_attrib(xml, "notify", default=""))
714950
def _init_xml(self, body):
        
        tree = etree.fromstring(body.encode(self.encoding), PARSER)
        # Extract and replace inner DIDL xml in tags
        for text in tree.xpath('.//text()[contains(., "DIDL")]'):
            item = text.getparent()
            didl_tree = etree.fromstring(item.text)
            if self.external_inner_xml:
                item.text = 'DIDL_REPLACEMENT_{0}'.format(len(self.inner_xml))
                self.inner_xml.append(didl_tree)
            else:
                item.text = None
                item.append(didl_tree)

        # Extract and replace inner DIDL xml in properties in inner xml
        for inner_tree in self.inner_xml:
            for item in inner_tree.xpath('//*[contains(@val, "DIDL")]'):
                if self.external_inner_xml:
                    didl_tree = etree.fromstring(item.attrib['val'])
                    item.attrib['val'] = 'DIDL_REPLACEMENT_{0}'.\
                        format(len(self.inner_xml))
                    self.inner_xml.append(didl_tree)

        self.body_formatted = etree.tostring(tree, pretty_print=True).decode(
            self.encoding)
962082
def xml(self, attribs = None,elements = None, skipchildren = False):
        """"""
        E = ElementMaker(namespace=NSFOLIA,nsmap={None: NSFOLIA, 'xml' : "http://www.w3.org/XML/1998/namespace"})

        if not attribs: attribs = {}
        if not elements: elements = []

        if self.id:
            attribs['id'] = self.id
            try:
                w = self.doc[self.id]
                attribs['t'] = w.text()
            except KeyError:
                pass

        e  = makeelement(E, '{' + NSFOLIA + '}' + self.XMLTAG, **attribs)
        return e
384054
private Object parseXmlElement(Element element) {
        if(element.getFirstChild() instanceof Text) {
            Text text = (Text) element.getFirstChild();
            return text.getData();
        }
        return element;
    }
1327330
def parse_xml_node(self, node):
        '''

        '''
        super(TargetExecutionContext, self).parse_xml_node(node)
        if node.hasAttributeNS(RTS_NS, 'id'):
            self.id = node.getAttributeNS(RTS_NS, 'id')
        else:
            self.id = ''
        return self
645776
def parse_xml_file(self, fileobj, id_generator=None):
        """"""
        root = etree.parse(fileobj).getroot()
        usage_id = self._usage_id_from_node(root, None, id_generator)
        return usage_id
1371006
def _parse(data, obj_name, attr_map):
    """"""
    parsed_xml = minidom.parseString(data)
    parsed_objects = []
    for obj in parsed_xml.getElementsByTagName(obj_name):
        parsed_obj = {}
        for (py_name, xml_name) in attr_map.items():
            parsed_obj[py_name] = _get_minidom_tag_value(obj, xml_name)
        parsed_objects.append(parsed_obj)
    return parsed_objects
1328795
def updateObjectFromXML(xml_doc, obj, mapping):
    
    nsmap = None
    if isinstance(mapping, dict):
        # The special key @namespaces is used to pass
        # namespaces and prefix mappings for xpath selectors.
        # e.g. {'x': 'http://example.com/namespace'}
        if '@namespaces' in mapping:
            nsmap = mapping['@namespaces']
    else:
        raise TypeError('Tag-to-property map must be a dict.')
    # Iterate over the keys of the translation dictionary from event objects
    # to xml objects, so we can update the fields with the new information
    for k, v in mapping.items():
        if k.startswith('@'):
            continue
        selected_text = None
        if isinstance(v, basestring):
            selector = v
        elif isinstance(v, list):
            selector = '/'.join(v)
        else:
            raise TypeError(
                'Invalid tag-to-property mapping dict: '
                'values must be strings or lists, not %s.' % (type(v),)
            )
        try:
            selected_text = xml_doc.xpath(selector, namespaces=nsmap)
            if isinstance(selected_text, list):
                selected_text = selected_text[0]
            selected_text = selected_text.text
            setattr(obj, k, selected_text)
        except IndexError:
            # Assume the value is missing. It's also possible that the
            # given selector is valid but wrong, but the more common
            # case is that the element is missing. To be consistent with
            # the prior implementation, empty resultsets just mean empty
            # attributes.
            continue
    return obj