Python xml.etree.ElementTree.iselement() Examples

The following are 28 code examples of xml.etree.ElementTree.iselement(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xml.etree.ElementTree , or try the search function .
Example #1
Source File: test_xml_etree.py    From BinderFilter with MIT License 6 votes vote down vote up
def check_element(element):
    if not ET.iselement(element):
        print "not an element"
    if not hasattr(element, "tag"):
        print "no tag member"
    if not hasattr(element, "attrib"):
        print "no attrib member"
    if not hasattr(element, "text"):
        print "no text member"
    if not hasattr(element, "tail"):
        print "no tail member"

    check_string(element.tag)
    check_mapping(element.attrib)
    if element.text is not None:
        check_string(element.text)
    if element.tail is not None:
        check_string(element.tail)
    for elem in element:
        check_element(elem)

# --------------------------------------------------------------------
# element tree tests 
Example #2
Source File: service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def CalculateDataLength(data):
  """Attempts to determine the length of the data to send. 
  
  This method will respond with a length only if the data is a string or
  and ElementTree element.

  Args:
    data: object If this is not a string or ElementTree element this funtion
        will return None.
  """
  if isinstance(data, str):
    return len(data)
  elif isinstance(data, list):
    return None
  elif ElementTree.iselement(data):
    return len(ElementTree.tostring(data))
  elif hasattr(data, 'read'):
    # If this is a file-like object, don't try to guess the length.
    return None
  else:
    return len(str(data)) 
Example #3
Source File: service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def __SendDataPart(data, connection):
  """This method is deprecated, use atom.http._send_data_part"""
  deprecated('call to deprecated function __SendDataPart')
  if isinstance(data, str):
    #TODO add handling for unicode.
    connection.send(data)
    return
  elif ElementTree.iselement(data):
    connection.send(ElementTree.tostring(data))
    return
  # Check to see if data is a file-like object that has a read method.
  elif hasattr(data, 'read'):
    # Read the file and send it a chunk at a time.
    while 1:
      binarydata = data.read(100000)
      if binarydata == '': break
      connection.send(binarydata)
    return
  else:
    # The data object was not a file.
    # Try to convert to a string and send the data.
    connection.send(str(data))
    return 
Example #4
Source File: __init__.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def SetXmlBlob(self, blob):
    """Sets the contents of the extendedProperty to XML as a child node.

    Since the extendedProperty is only allowed one child element as an XML
    blob, setting the XML blob will erase any preexisting extension elements
    in this object.

    Args:
      blob: str, ElementTree Element or atom.ExtensionElement representing
            the XML blob stored in the extendedProperty.
    """
    # Erase any existing extension_elements, clears the child nodes from the
    # extendedProperty.
    self.extension_elements = []
    if isinstance(blob, atom.ExtensionElement):
      self.extension_elements.append(blob)
    elif ElementTree.iselement(blob):
      self.extension_elements.append(atom._ExtensionElementFromElementTree(
          blob))
    else:
      self.extension_elements.append(atom.ExtensionElementFromString(blob)) 
Example #5
Source File: service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def __SendDataPart(data, connection):
  """This method is deprecated, use atom.http._send_data_part"""
  deprecated('call to deprecated function __SendDataPart')
  if isinstance(data, str):
    #TODO add handling for unicode.
    connection.send(data)
    return
  elif ElementTree.iselement(data):
    connection.send(ElementTree.tostring(data))
    return
  # Check to see if data is a file-like object that has a read method.
  elif hasattr(data, 'read'):
    # Read the file and send it a chunk at a time.
    while 1:
      binarydata = data.read(100000)
      if binarydata == '': break
      connection.send(binarydata)
    return
  else:
    # The data object was not a file.
    # Try to convert to a string and send the data.
    connection.send(str(data))
    return 
Example #6
Source File: __init__.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def SetXmlBlob(self, blob):
    """Sets the contents of the extendedProperty to XML as a child node.

    Since the extendedProperty is only allowed one child element as an XML
    blob, setting the XML blob will erase any preexisting extension elements
    in this object.

    Args:
      blob: str, ElementTree Element or atom.ExtensionElement representing
            the XML blob stored in the extendedProperty.
    """
    # Erase any existing extension_elements, clears the child nodes from the
    # extendedProperty.
    self.extension_elements = []
    if isinstance(blob, atom.ExtensionElement):
      self.extension_elements.append(blob)
    elif ElementTree.iselement(blob):
      self.extension_elements.append(atom._ExtensionElementFromElementTree(
          blob))
    else:
      self.extension_elements.append(atom.ExtensionElementFromString(blob)) 
Example #7
Source File: service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def CalculateDataLength(data):
  """Attempts to determine the length of the data to send. 
  
  This method will respond with a length only if the data is a string or
  and ElementTree element.

  Args:
    data: object If this is not a string or ElementTree element this funtion
        will return None.
  """
  if isinstance(data, str):
    return len(data)
  elif isinstance(data, list):
    return None
  elif ElementTree.iselement(data):
    return len(ElementTree.tostring(data))
  elif hasattr(data, 'read'):
    # If this is a file-like object, don't try to guess the length.
    return None
  else:
    return len(str(data)) 
Example #8
Source File: service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def __SendDataPart(data, connection):
  """This method is deprecated, use atom.http._send_data_part"""
  deprecated('call to deprecated function __SendDataPart')
  if isinstance(data, str):
    #TODO add handling for unicode.
    connection.send(data)
    return
  elif ElementTree.iselement(data):
    connection.send(ElementTree.tostring(data))
    return
  # Check to see if data is a file-like object that has a read method.
  elif hasattr(data, 'read'):
    # Read the file and send it a chunk at a time.
    while 1:
      binarydata = data.read(100000)
      if binarydata == '': break
      connection.send(binarydata)
    return
  else:
    # The data object was not a file.
    # Try to convert to a string and send the data.
    connection.send(str(data))
    return 
Example #9
Source File: __init__.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def SetXmlBlob(self, blob):
    """Sets the contents of the extendedProperty to XML as a child node.

    Since the extendedProperty is only allowed one child element as an XML
    blob, setting the XML blob will erase any preexisting extension elements
    in this object.

    Args:
      blob: str, ElementTree Element or atom.ExtensionElement representing
            the XML blob stored in the extendedProperty.
    """
    # Erase any existing extension_elements, clears the child nodes from the
    # extendedProperty.
    self.extension_elements = []
    if isinstance(blob, atom.ExtensionElement):
      self.extension_elements.append(blob)
    elif ElementTree.iselement(blob):
      self.extension_elements.append(atom._ExtensionElementFromElementTree(
          blob))
    else:
      self.extension_elements.append(atom.ExtensionElementFromString(blob)) 
Example #10
Source File: test_xml_etree.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check_element(element):
    if not ET.iselement(element):
        print "not an element"
    if not hasattr(element, "tag"):
        print "no tag member"
    if not hasattr(element, "attrib"):
        print "no attrib member"
    if not hasattr(element, "text"):
        print "no text member"
    if not hasattr(element, "tail"):
        print "no tail member"

    check_string(element.tag)
    check_mapping(element.attrib)
    if element.text is not None:
        check_string(element.text)
    if element.tail is not None:
        check_string(element.tail)
    for elem in element:
        check_element(elem)

# --------------------------------------------------------------------
# element tree tests 
Example #11
Source File: test_xml_etree.py    From oss-ftp with MIT License 6 votes vote down vote up
def check_element(element):
    if not ET.iselement(element):
        print "not an element"
    if not hasattr(element, "tag"):
        print "no tag member"
    if not hasattr(element, "attrib"):
        print "no attrib member"
    if not hasattr(element, "text"):
        print "no text member"
    if not hasattr(element, "tail"):
        print "no tail member"

    check_string(element.tag)
    check_mapping(element.attrib)
    if element.text is not None:
        check_string(element.text)
    if element.tail is not None:
        check_string(element.tail)
    for elem in element:
        check_element(elem)

# --------------------------------------------------------------------
# element tree tests 
Example #12
Source File: validate.py    From streamlink with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get(item, default=None):
    """Get item from value (value[item]).

    If the item is not found, return the default.

    Handles XML elements, regex matches and anything that has __getitem__.
    """

    def getter(value):
        if ET.iselement(value):
            value = value.attrib

        try:
            # Use .group() if this is a regex match object
            if _is_re_match(value):
                return value.group(item)
            else:
                return value[item]
        except (KeyError, IndexError):
            return default
        except (TypeError, AttributeError) as err:
            raise ValueError(err)

    return transform(getter) 
Example #13
Source File: parser.py    From teye_scanner_for_book with GNU General Public License v3.0 6 votes vote down vote up
def __format_element(elt_data):
        """
            Private method which ensures that a XML portion to be parsed is
            of type xml.etree.ElementTree.Element.
            If elt_data is a string, then it is converted to an
            XML Element type.

            :param elt_data: XML Element to be parsed or string
            to be converted to a XML Element

            :return: Element
        """
        if isinstance(elt_data, str):
            try:
                xelement = ET.fromstring(elt_data)
            except:
                raise NmapParserException("Error while trying "
                                          "to instanciate XML Element from "
                                          "string {0}".format(elt_data))
        elif ET.iselement(elt_data):
            xelement = elt_data
        else:
            raise NmapParserException("Error while trying to parse supplied "
                                      "data: unsupported format")
        return xelement 
Example #14
Source File: xmltopicdefnprovider.py    From MARA_Framework with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_elem(elem):
    """Assume an ETree.Element object or a string representation.
    Return the ETree.Element object"""
    if not ET.iselement(elem):
        try:
            elem = ET.fromstring(elem)
        except:
            py2and3.print_("Value Error", elem)
            raise ValueError("Cannot convert to element")
    return elem 
Example #15
Source File: parse.py    From eapeak with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_client_info(self, client, newClient, _ElementTree):
		eaptypes = client.find('eap-types')
		if ElementTree.iselement(eaptypes):
			eaptypes = eaptypes.text
			if eaptypes != None:
				for eaptype in eaptypes.strip().split(','):
					if eaptype.isdigit():
						newClient.addEapType(int(eaptype))
		identities = client.findall('identity') or []
		for identity in identities:
			tmp = identity.get('eap-type')
			if tmp.isdigit():
				newClient.add_identity(int(tmp), identity.text.strip())
		mschaps = client.findall('mschap') or []
		for mschap in mschaps:
			newClient.add_ms_chap_info(
				int(mschap.get('eap-type')),
				binascii.a2b_hex(mschap.find('challenge').text.strip().replace(':', '')),
				binascii.a2b_hex(mschap.find('response').text.strip().replace(':', '')),
				mschap.get('identity')
			)
		wpsXMLData = client.find('wps-data')
		if ElementTree.iselement(wpsXMLData):
			wpsData = wpsDataHolder()
			for elem in wpsXMLData:
				key = elem.tag.replace('-', ' ')
				value = elem.text.strip()
				if elem.get('encoding') == 'hex':
					wpsData[key] = binascii.a2b_hex(value)
				elif elem.get('encoding') == 'base64':
					wpsData[key] = base64.standard_b64decode(value)
				else:
					wpsData[key] = value
			if len(wpsData):
				newClient.wpsData = wpsData 
Example #16
Source File: parse.py    From eapeak with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_network_info(self, network, newNetwork, _ElementTree, ssid):
		for bssid in network.findall('BSSID'):
			bssid = bssid.text.strip()
			newNetwork.add_BSSID(bssid)
			if ssid != UNKNOWN_SSID_NAME:
				self.BSSIDToSSIDMap[bssid] = ssid
			else:
				self.BSSIDToSSIDMap[bssid] = bssid
				self.OrphanedBSSIDs.append(bssid)
		eaptypes = network.find('SSID').find('eap-types')
		if ElementTree.iselement(eaptypes):
			for eaptype in eaptypes.text.strip().split(','):
				if eaptype.isdigit():
					newNetwork.addEapType(int(eaptype))
		expandedVendorIDs = network.find('SSID').find('expanded-vendor-ids')
		if ElementTree.iselement(expandedVendorIDs):
			for vendorid in expandedVendorIDs.text.strip().split(','):
				if vendorid.isdigit():
					newNetwork.add_expanded_vendor_id(int(vendorid))
		wpsXMLData = network.find('wps-data')
		if ElementTree.iselement(wpsXMLData):
			wpsData = wpsDataHolder()
			for elem in wpsXMLData:
				key = elem.tag.replace('-', ' ')
				value = elem.text.strip()
				encoding = elem.get('encoding')
				if encoding == 'hex':
					wpsData[key] = binascii.a2b_hex(value)
				elif encoding == 'base64':
					wpsData[key] = base64.standard_b64decode(value)
				else:
					wpsData[key] = value
			if len(wpsData):
				newNetwork.wpsData = wpsData 
Example #17
Source File: validate.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def xml_find(xpath):
    """Find a XML element via xpath."""
    def xpath_find(value):
        validate(ET.iselement, value)
        value = value.find(xpath)
        if value is None:
            raise ValueError("XPath '{0}' did not return an element".format(xpath))

        return validate(ET.iselement, value)

    return transform(xpath_find) 
Example #18
Source File: validate.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def xml_findall(xpath):
    """Find a list of XML elements via xpath."""
    def xpath_findall(value):
        validate(ET.iselement, value)
        return value.findall(xpath)

    return transform(xpath_findall) 
Example #19
Source File: validate.py    From streamlink with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def validate_xml_element(schema, value):
    validate(ET.iselement, value)
    new = ET.Element(value.tag, attrib=value.attrib)

    if schema.attrib is not None:
        try:
            new.attrib = validate(schema.attrib, value.attrib)
        except ValueError as err:
            raise ValueError("Unable to validate XML attributes: {0}".format(err))

    if schema.tag is not None:
        try:
            new.tag = validate(schema.tag, value.tag)
        except ValueError as err:
            raise ValueError("Unable to validate XML tag: {0}".format(err))

    if schema.text is not None:
        try:
            new.text = validate(schema.text, value.text)
        except ValueError as err:
            raise ValueError("Unable to validate XML text: {0}".format(err))

    for child in value:
        new.append(child)

    return new 
Example #20
Source File: parser.py    From teye_scanner_for_book with GNU General Public License v3.0 5 votes vote down vote up
def __format_attributes(elt_data):
        """
            Private method which converts a single XML tag to a python dict.
            It also checks that the elt_data given as argument is of type
            xml.etree.ElementTree.Element

            :param elt_data: XML Element to be parsed or string
            to be converted to a XML Element

            :return: Element
        """

        rval = {}
        if not ET.iselement(elt_data):
            raise NmapParserException("Error while trying to parse supplied "
                                      "data attributes: format is not XML or "
                                      "XML tag is empty")
        try:
            for dkey in elt_data.keys():
                rval[dkey] = elt_data.get(dkey)
                if rval[dkey] is None:
                    raise NmapParserException("Error while trying to build-up "
                                              "element attributes: empty "
                                              "attribute {0}".format(dkey))
        except:
            raise
        return rval 
Example #21
Source File: myplex.py    From python-plexapi with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sections(self):
        """ Returns a list of all :class:`~plexapi.myplex.Section` objects shared with this user.
        """
        url = MyPlexAccount.FRIENDSERVERS.format(machineId=self.machineIdentifier, serverId=self.id)
        data = self._server.query(url)
        sections = []

        for section in data.iter('Section'):
            if ElementTree.iselement(section):
                sections.append(Section(self, section, url))

        return sections 
Example #22
Source File: gpx.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def open(self, string_or_file):
        if isinstance(string_or_file, basestring):
            string_or_file = ElementTree.fromstring(string_or_file)
        elif not ElementTree.iselement(string_or_file):
            string_or_file = ElementTree.parse(string_or_file)
        if string_or_file.getroot().tag == self._get_qname('gpx'):
            self._root = string_or_file.getroot() 
Example #23
Source File: rdf.py    From luscan-devel with GNU General Public License v2.0 5 votes vote down vote up
def find(self, document):
        if isinstance(document, basestring):
            document = ElementTree.fromstring(document)
        elif not ElementTree.iselement(document):
            document = ElementTree.parse(document)
        
        point_qname = self._get_qname(self.POINT_CLASS)
        lat_qname = self._get_qname(self.LATITUDE_PROPERTY)
        long_qname = self._get_qname(self.LONGITUDE_PROPERTY)
        alt_qname = self._get_qname(self.ALTITUDE_PROPERTY)
        
        queue = [document]
        while queue:
            element = queue.pop()
            if not self.point_class or element.tag == point_qname:
                lat_el = element.find(lat_qname)
                long_el = element.find(long_qname)
                alt_el = element.find(alt_qname)
                if lat_el is not None and long_el is not None:
                    latitude = lat_el.text
                    longitude = long_el.text
                    altitude = alt_el and alt_el.text
                    try:
                        point = Point((latitude, longitude, altitude))
                    except (TypeError, ValueError):
                        if not self.ignore_invalid:
                            raise
                    else:
                        yield Location(None, point)
                
                queue.extend(reversed(element)) 
Example #24
Source File: __init__.py    From xrt with MIT License 5 votes vote down vote up
def iterateImport(self, view, rootModel, rootImport):
        if ET.iselement(rootImport):
            self.ntab += 1
            for childImport in rootImport:
                itemType = str(childImport.attrib['type'])
                itemTag = str(childImport.tag)
                itemText = str(childImport.text)
                child0 = qt.QStandardItem(itemTag)
                if itemType == "flat":
                    if rootModel.model() != self.beamModel:
                        child0 = rootModel.appendRow(child0)
                    else:
                        rootModel.appendRow([child0, None, None, None])
                elif itemType == "value":
                    child0 = self.addValue(rootModel, itemTag)
                    if self.ntab == 1:
                        self.capitalize(view, child0)
                elif itemType == "prop":
                    child0 = self.addProp(rootModel, itemTag)
                elif itemType == "object":
                    child0, child1 = self.addObject(view,
                                                    rootModel,
                                                    itemText)
                elif itemType == "param":
                    child0, child1 = self.addParam(rootModel,
                                                   itemTag,
                                                   itemText)
                self.iterateImport(view, child0, childImport)
            self.ntab -= 1
        else:
            pass 
Example #25
Source File: utils.py    From rucio with Apache License 2.0 4 votes vote down vote up
def parse_replicas_metalink(root):
    """
    Transforms the metalink tree into a list of dictionaries where
    each dictionary describes a file with its replicas.
    Will be called by parse_replicas_from_file and parse_replicas_from_string.

    :param root: root node of the metalink tree

    :returns: a list with a dictionary for each file
    """
    files = []

    # metalink namespace
    ns = '{urn:ietf:params:xml:ns:metalink}'
    str_to_bool = {'true': True, 'True': True, 'false': False, 'False': False}

    # loop over all <file> tags of the metalink string
    for file_tag_obj in root.findall(ns + 'file'):
        # search for identity-tag
        identity_tag_obj = file_tag_obj.find(ns + 'identity')
        if not ElementTree.iselement(identity_tag_obj):
            raise InputValidationError('Failed to locate identity-tag inside %s' % ElementTree.tostring(file_tag_obj))

        cur_file = {'did': identity_tag_obj.text,
                    'adler32': None,
                    'md5': None,
                    'sources': []}

        parent_dids = set()
        parent_dids_tag_obj = file_tag_obj.find(ns + 'parents')
        if ElementTree.iselement(parent_dids_tag_obj):
            for did_tag_obj in parent_dids_tag_obj.findall(ns + 'did'):
                parent_dids.add(did_tag_obj.text)
        cur_file['parent_dids'] = parent_dids

        size_tag_obj = file_tag_obj.find(ns + 'size')
        cur_file['bytes'] = int(size_tag_obj.text) if ElementTree.iselement(size_tag_obj) else None

        for hash_tag_obj in file_tag_obj.findall(ns + 'hash'):
            hash_type = hash_tag_obj.get('type')
            if hash_type:
                cur_file[hash_type] = hash_tag_obj.text

        for url_tag_obj in file_tag_obj.findall(ns + 'url'):
            key_rename_map = {'location': 'rse'}
            src = {}
            for k, v in url_tag_obj.items():
                k = key_rename_map.get(k, k)
                src[k] = str_to_bool.get(v, v)
            src['pfn'] = url_tag_obj.text
            cur_file['sources'].append(src)

        files.append(cur_file)

    return files 
Example #26
Source File: parse.py    From eapeak with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def parse_xml_files(self, xmlFiles, quite=True):
		"""
		Load EAPeak/Kismet style XML files for information.  This is
		faster than parsing large PCap files.
		"""
		if not hasattr(xmlFiles, '__iter__'):
			if isinstance(xmlFiles, str):
				xmlFiles = [xmlFiles]
			else:
				return
		for xmlfile in xmlFiles:
			if not os.path.isfile(xmlfile):
				if not quite:
					sys.stdout.write("Skipping File {0}: File Not Found\n".format(xmlfile))
					sys.stdout.flush()
				continue
			elif not os.access(xmlfile, os.R_OK):
				if not quite:
					sys.stdout.write("Skipping File {0}: Permissions Issue\n".format(xmlfile))
					sys.stdout.flush()
				continue
			sys.stdout.write("Parsing XML  File: {0}".format(xmlfile))
			sys.stdout.flush()
			e = ElementTree.parse(xmlfile)
			for network in e.findall('wireless-network'):
				ssid = network.find('SSID')
				if not ElementTree.iselement(ssid) or not ElementTree.iselement(ssid.find('type')):
					continue
				elif ssid.find('type').text.strip() != 'Beacon':
					continue
				ssid = ssid.find('essid')
				if ElementTree.iselement(ssid):
					if ssid.text is None:
						ssid = UNKNOWN_SSID_NAME
					else:
						ssid = ssid.text.strip()
					newNetwork = eapeak.networks.WirelessNetwork(ssid)
				else:
					continue
				self.get_network_info(network, newNetwork, ElementTree, ssid)
				for client in network.findall('wireless-client'):
					bssid = client.find('client-bssid')
					if ElementTree.iselement(bssid):
						bssid = bssid.text.strip()
					else:
						continue
					client_mac = client.find('client-mac').text.strip()
					newClient = eapeak.clients.WirelessClient(bssid, client_mac)
					self.get_client_info(client, newClient, ElementTree)
					newNetwork.add_client(newClient)
				self.find_certs(network, newNetwork)
				if ssid != UNKNOWN_SSID_NAME:
					self.KnownNetworks[ssid] = newNetwork
				else:
					self.KnownNetworks[bssid] = newNetwork
#				if ssid == UNKNOWN_SSID_NAME and len(network.findall('BSSID')) > 1:
#					there will be an issue with where to store the single network object.
#					If there is a client and the network is added to KnownNetworks each time this occurs then the client will appear to under each network but only
#					be associated with the single BSSID.  This problem needs to be addressed and throughly tested.
			sys.stdout.write(" Done\n")
			sys.stdout.flush() 
Example #27
Source File: epf.py    From canopen with MIT License 4 votes vote down vote up
def import_epf(epf):
    """Import an EPF file.

    :param epf:
        Either a path to an EPF-file, a file-like object, or an instance of
        :class:`xml.etree.ElementTree.Element`.

    :returns:
        The Object Dictionary.
    :rtype: canopen.ObjectDictionary
    """
    od = objectdictionary.ObjectDictionary()
    if etree.iselement(epf):
        tree = epf
    else:
        tree = etree.parse(epf).getroot()

    # Find and set default bitrate
    can_config = tree.find("Configuration/CANopen")
    if can_config is not None:
        bitrate = can_config.get("BitRate", "250")
        bitrate = bitrate.replace("U", "")
        od.bitrate = int(bitrate) * 1000

    # Parse Object Dictionary
    for group_tree in tree.iterfind("Dictionary/Parameters/Group"):
        name = group_tree.get("SymbolName")
        parameters = group_tree.findall("Parameter")
        index = int(parameters[0].get("Index"), 0)

        if len(parameters) == 1:
            # Simple variable
            var = build_variable(parameters[0])
            # Use top level index name instead
            var.name = name
            od.add_object(var)
        elif len(parameters) == 2 and parameters[1].get("ObjectType") == "ARRAY":
            # Array
            arr = objectdictionary.Array(name, index)
            for par_tree in parameters:
                var = build_variable(par_tree)
                arr.add_member(var)
            description = group_tree.find("Description")
            if description is not None:
                arr.description = description.text
            od.add_object(arr)
        else:
            # Complex record
            record = objectdictionary.Record(name, index)
            for par_tree in parameters:
                var = build_variable(par_tree)
                record.add_member(var)
            description = group_tree.find("Description")
            if description is not None:
                record.description = description.text
            od.add_object(record)

    return od 
Example #28
Source File: util.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
def concat(docs):
    """
    Concatenate together the contents of multiple documents from a
    single corpus, using an appropriate concatenation function.  This
    utility function is used by corpus readers when the user requests
    more than one document at a time.
    """
    if len(docs) == 1:
        return docs[0]
    if len(docs) == 0:
        raise ValueError('concat() expects at least one object!')

    types = set(d.__class__ for d in docs)

    # If they're all strings, use string concatenation.
    if all(isinstance(doc, string_types) for doc in docs):
        return ''.join(docs)

    # If they're all corpus views, then use ConcatenatedCorpusView.
    for typ in types:
        if not issubclass(typ, (StreamBackedCorpusView, ConcatenatedCorpusView)):
            break
    else:
        return ConcatenatedCorpusView(docs)

    # If they're all lazy sequences, use a lazy concatenation
    for typ in types:
        if not issubclass(typ, AbstractLazySequence):
            break
    else:
        return LazyConcatenation(docs)

    # Otherwise, see what we can do:
    if len(types) == 1:
        typ = list(types)[0]

        if issubclass(typ, list):
            return reduce((lambda a, b: a + b), docs, [])

        if issubclass(typ, tuple):
            return reduce((lambda a, b: a + b), docs, ())

        if ElementTree.iselement(typ):
            xmltree = ElementTree.Element('documents')
            for doc in docs:
                xmltree.append(doc)
            return xmltree

    # No method found!
    raise ValueError("Don't know how to concatenate types: %r" % types)


######################################################################
# { Corpus View for Pickled Sequences
######################################################################