Parse a VocabularyKey from an Xml as per Healthvault
            schema.

            :param key_xml: lxml.etree.Element representing a single VocabularyKey
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()
253591
def etree(self, data, root=None):
        ''''''
        result = self.list() if root is None else root
        if isinstance(data, (self.dict, dict)):
            for key, value in data.items():
                value_is_list = isinstance(value, (self.list, list))
                value_is_dict = isinstance(value, (self.dict, dict))
                # Add attributes and text to result (if root)
                if root is not None:
                    # Handle attribute prefixes (BadgerFish)
                    if self.attr_prefix is not None:
                        if key.startswith(self.attr_prefix):
                            key = key.lstrip(self.attr_prefix)
                            # @xmlns: {$: xxx, svg: yyy} becomes xmlns="xxx" xmlns:svg="yyy"
                            if value_is_dict:
                                raise ValueError('XML namespaces not yet supported')
                            else:
                                result.set(key, self._tostring(value))
                            continue
                    # Handle text content (BadgerFish, GData)
                    if self.text_content is not None:
                        if key == self.text_content:
                            result.text = self._tostring(value)
                            continue
                    # Treat scalars as text content, not children (GData)
                    if self.attr_prefix is None and self.text_content is not None:
                        if not value_is_dict and not value_is_list:
                            result.set(key, self._tostring(value))
                            continue
                # Add other keys as one or more children
                values = value if value_is_list else [value]
                for value in values:
                    elem = self.element(key)
                    if elem is None:
                        continue
                    result.append(elem)
                    # Treat scalars as text content, not children (Parker)
                    if not isinstance(value, (self.dict, dict, self.list, list)):
                        if self.text_content:
                            value = {self.text_content: value}
                    self.etree(value, root=elem)
        else:
            if self.text_content is None and root is not None:
                root.text = self._tostring(data)
            else:
                elem = self.element(self._tostring(data))
                if elem is not None:
                    result.append(elem)
        return result
638303
def lookup_key(self):
        
        parts = set()
        for node in self.simple_selectors:
            for token in node.tokens:
                if token[0] not in ':[':
                    parts.add(token)

        if not parts:
            # Should always have at least ONE key; selectors with no elements,
            # no classes, and no ids can be indexed as None to avoid a scan of
            # every selector in the entire document
            parts.add(None)

        return frozenset(parts)
290258
def parse_xml(contents, name)
      hash = Hash.from_xml(contents)
      hash = hash[name] if hash.size == 1 && hash.key?(name)  # xml document could have root tag matching the file name.
      RConfig::PropertiesFile.parse_references(hash)
    end
216941
def create_keypair(self, xml_bytes):
        
        keypair_data = XML(xml_bytes)
        key_name = keypair_data.findtext("keyName")
        key_fingerprint = keypair_data.findtext("keyFingerprint")
        key_material = keypair_data.findtext("keyMaterial")
        return model.Keypair(key_name, key_fingerprint, key_material)
827297
def key_is_valid_xml(key):
    """"""
    LOG.info('Inside key_is_valid_xml(). Testing "%s"' % (unicode_me(key)))
    test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % (key, key)
    try:
        parseString(test_xml)
        return True
    except Exception: # minidom does not implement exceptions well
        return False
486395
def dom_to_dict(root_node):

    

    # Remove namespaces from tagname

    tag = root_node.tagName

    if ":" in tag:

        tag = tag.split(":")[1]

    root_dict = {
        tag: {}
    }

    node_dict = root_dict[tag]

    # Set attributes

    if root_node.hasAttributes():

        for key in list(root_node.attributes.keys()):

            node_dict[key] = root_node.getAttribute(key)

    # Check out child nodes

    for child in root_node.childNodes:

        if child.nodeType == root_node.TEXT_NODE:

            # This is the content

            node_dict['_content'] = child.data

        else:

            subnode_dict = dom_to_dict(child)

            child_tag = child.tagName

            if ":" in child_tag:

                child_tag = child_tag.split(":")[1]

            new_val = subnode_dict[child_tag]

            # If we have several child with same name, put them in a list.

            if child_tag in node_dict:
                prev_val = node_dict[child_tag]

                if type(prev_val) != list:
                    node_dict[child_tag] = [prev_val]

                node_dict[child_tag].append(new_val)

            else:
                node_dict[child_tag] = new_val

    return root_dict
139955
def parse_voc_rec(filename):
    
    import xml.etree.ElementTree as ET
    tree = ET.parse(filename)
    objects = []
    for obj in tree.findall('object'):
        obj_dict = dict()
        obj_dict['name'] = obj.find('name').text
        obj_dict['difficult'] = int(obj.find('difficult').text)
        bbox = obj.find('bndbox')
        obj_dict['bbox'] = [int(bbox.find('xmin').text),
                            int(bbox.find('ymin').text),
                            int(bbox.find('xmax').text),
                            int(bbox.find('ymax').text)]
        objects.append(obj_dict)
    return objects
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)]"
            )
272292
def hash_from_xml(data, type)
      hash = {}
      case type
      when :attributes
        data.attributes.each do |k, v|
          hash[name2sym(k)] = str_clean(v)
        end
      when :children
        data.each do |f|
          hash[name2sym(f[0])] = f[1]
        end
      when :element
        data.elements.each do |child|
          if child.name == 'possibleLengths'
            hash[Core::POSSIBLE_PATTERN] =
                possible_length_regex(hash_from_xml(child, :attributes))
          else
            hash[name2sym(child.name)] = str_clean(child.children.first)
          end
        end
      end
      hash
    end
642554
def load_xml_conf(self, xml_file, id):
        '''
        
        '''

        # converting nutch-site.xml to key:value pairs
        import xml.etree.ElementTree as ET
        tree = ET.parse(xml_file)
        params = {}
        for prop in tree.getroot().findall(".//property"):
            params[prop.find('./name').text.strip()] = prop.find('./value').text.strip()
        return self.proxy.Configs().create(id, configData=params)
610185
def import_from_xml(self, xml):
        '''
        
        '''
        self._import_orgid(xml)
        self._import_parents_from_xml(xml)
        self._import_instances_from_xml(xml)
        self._import_common_name(xml)
        self._import_synonyms(xml)
        self._import_dblinks(xml)
1333409
def ln_from_etree(self, ln_element, context=''):
        
        ln = {}
        # grab all understood attributes into ln dict
        for att in ('hash', 'href', 'length', 'modified',
                    'path', 'rel', 'pri', 'mime_type'):
            xml_att = self._xml_att_name(att)
            val = ln_element.attrib.get(xml_att, None)
            if (val is not None):
                ln[att] = val
        # now do some checks and conversions...
        # href (MANDATORY)
        if ('href' not in ln):
            raise SitemapParseError(
                "Missing href in <rs:ln> in %s" %
                (context))
        # rel (MANDATORY)
        if ('rel' not in ln):
            raise SitemapParseError("Missing rel in <rs:ln> in %s" % (context))
        # length in bytes
        if ('length' in ln):
            try:
                ln['length'] = int(ln['length'])
            except ValueError as e:
                raise SitemapParseError(
                    "Invalid length attribute value in <rs:ln> for %s" %
                    (context))
        # pri - priority, must be a number between 1 and 999999
        if ('pri' in ln):
            try:
                ln['pri'] = int(ln['pri'])
            except ValueError as e:
                raise SitemapParseError(
                    "Invalid pri attribute in <rs:ln> for %s" %
                    (context))
            if (ln['pri'] < 1 or ln['pri'] > 999999):
                raise SitemapParseError(
                    "Bad pri attribute value in <rs:ln> for %s" %
                    (context))
        return(ln)
897835
def xml_str_to_dict(s):
    
    xml = minidom.parseString(s)
    return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)
978349
def _elementtree_to_dict(self, element):
        
        node = {}
        text = getattr(element, 'text')
        if text is not None:
            text = text.strip()
            if len(text) != 0:
                node['text'] = text
        node.update(element.items())  # element's attributes
        child_nodes = {}
        for child in element:  # element's children
            child_nodes.setdefault(child.tag, []).append(
                self._elementtree_to_dict(child))
        # convert all single-element lists into non-lists
        for key, value in child_nodes.items():
            if len(value) == 1:
                child_nodes[key] = value[0]
        node.update(child_nodes.items())
        return node
1171526
def _load_xml(self):
        
        if self._xml is not None:
            return
        matcher = "\[(?:Normal|Conditional) Substitution\(index=(\d+), type=\d+\)\]"
        self._xml = re.sub(matcher, "{\\1:}",
                           self._template_node.template_format().replace("{", "{{").replace("}", "}}"))
280749
def pydict2xmlstring(metadata_dict, **kwargs):
    """"""
    ordering = kwargs.get('ordering', UNTL_XML_ORDER)
    root_label = kwargs.get('root_label', 'metadata')
    root_namespace = kwargs.get('root_namespace', None)
    elements_namespace = kwargs.get('elements_namespace', None)
    namespace_map = kwargs.get('namespace_map', None)
    root_attributes = kwargs.get('root_attributes', None)
    # Set any root namespace and namespace map.
    if root_namespace and namespace_map:
        root = Element(root_namespace + root_label, nsmap=namespace_map)
    elif namespace_map:
        root = Element(root_label, nsmap=namespace_map)
    else:
        root = Element(root_label)
    # Set any root element attributes.
    if root_attributes:
        for key, value in root_attributes.items():
            root.attrib[key] = value
    # Create an XML structure from field list.
    for metadata_key in ordering:
        if metadata_key in metadata_dict:
            for element in metadata_dict[metadata_key]:
                if 'content' in element and 'qualifier' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'qualifier': element['qualifier']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element and 'role' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'role': element['role']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element and 'scheme' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        attribs={'scheme': element['scheme']},
                        namespace=elements_namespace,
                    )
                elif 'content' in element:
                    create_dict_subelement(
                        root,
                        metadata_key,
                        element['content'],
                        namespace=elements_namespace,
                    )
    # Create the XML tree.
    return '<?xml version="1.0" encoding="UTF-8"?>\n' + tostring(
        root,
        pretty_print=True
    )