Python xml.etree.cElementTree.iselement() Examples

The following are 14 code examples of xml.etree.cElementTree.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.cElementTree , or try the search function .
Example #1
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 #2
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 #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: 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 #5
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 #6
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 #7
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 #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: 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 #10
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 #11
Source File: xml_.py    From ryu with Apache License 2.0 5 votes vote down vote up
def to_ele(x):
    "Convert and return the :class:`~xml.etree.ElementTree.Element` for the XML document *x*. If *x* is already an :class:`~xml.etree.ElementTree.Element` simply returns that."
    return x if ET.iselement(x) else ET.fromstring(x) 
Example #12
Source File: base_xml.py    From lpts with GNU General Public License v2.0 5 votes vote down vote up
def remove_element(self, node, element):
        '''
        @attention: 确定是否存在node和element
        '''
        if ET.iselement(element):
            node.remove(element) 
Example #13
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 #14
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
######################################################################