我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用xml.etree.cElementTree.iselement()。
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))
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
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))
def from_xml(self, elem, handle=None): """This method creates the object from the xml representation of the Method object.""" self._handle = handle if elem.attrib: for attr_name, attr_value in imcgenutils.iteritems(elem.attrib): self.attr_set(imcgenutils.convert_to_python_var_name(attr_name), str(attr_value)) child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not Et.iselement(child_elem): continue cln = imcgenutils.word_u(child_elem.tag) child = imccoreutils.get_imc_obj(cln, child_elem) self._child.append(child) child.from_xml(child_elem, handle)
def from_xml(self, elem, handle=None): """This method creates the object from the xml representation of the Method object.""" self._handle = handle if elem.attrib: for attr_name, attr_value in ucscgenutils.iteritems(elem.attrib): self.attr_set( ucscgenutils.convert_to_python_var_name(attr_name), str(attr_value)) child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not ET.iselement(child_elem): continue cln = ucscgenutils.word_u(child_elem.tag) child = ucsccoreutils.get_ucsc_obj(cln, child_elem) self._child.append(child) child.from_xml(child_elem, handle)
def set_prefixes(self, elem, prefix_map): # check if this is a tree wrapper if not ElementTree.iselement(elem): elem = elem.getroot() # build uri map and add to root element uri_map = {} for prefix, uri in prefix_map.items(): uri_map[uri] = prefix elem.set("xmlns:" + prefix, uri) # fixup all elements in the tree memo = {} for elem in elem.getiterator(): self.fixup_element_prefixes(elem, uri_map, memo)
def __new__(cls,tag,thing = None,*args,**kwargs): if hasattr(tag,'__xml__'): return tag.__xml__() self = object.__new__(xml) if cElementTree.iselement(tag): self.__content = tag elif isinstance(tag,cElementTree.ElementTree): self.__content = tag.getroot() elif is_file(tag): self.__content = cElementTree.parse(tag).getroot() elif isinstance(tag,str) and len(tag) > 0 and tag[0] == '<': self.__content = cElementTree.fromstring(tag) else: if type(tag) != str: raise TypeError("Cannot convert %s object to xml" % str(type(tag))) self.__content = cElementTree.fromstring('<%s/>' % tag) if is_text(thing) or type(thing) == int: self.__content.text = text(thing) elif thing != None: self.append(xml(thing)) for subthing in args: self.append(xml(subthing)) for key,value in kwargs.items(): if key == '__class' or key == 'klass': self['class'] = value else: self[key] = value if '{' in self.__content.tag: self.__prefix = PREFIX_PAT.search(self.__content.tag).groups()[0] else: self.__prefix = '' return self
def from_xml(self, elem, handle=None): """Method updates/fills the object from the xml representation of the external method object. """ self._handle = handle if elem.attrib: for attr_name, attr_value in imcgenutils.iteritems(elem.attrib): if attr_name in self.__property_map: attr = self.__property_map[attr_name] method_prop_meta = self.__property_meta[attr] if method_prop_meta.inp_out == "Input" or ( method_prop_meta.is_complex_type): continue self.set_attr(attr, str(attr_value)) elif attr_name in ExternalMethod._external_method_attrs: self.set_attr( ExternalMethod._external_method_attrs[attr_name], str(attr_value)) child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not ET.iselement(child_elem): continue child_name = child_elem.tag if child_name in self.__property_map: child_name = self.__property_map[child_name] method_prop_meta = self.__property_meta[ child_name] if method_prop_meta.inp_out == "Output" and \ (method_prop_meta.is_complex_type): child_obj = imccoreutils.get_imc_obj( method_prop_meta.field_type, child_elem) if child_obj: self.set_attr(child_name, child_obj) # print child_method_obj.__dict__ child_obj.from_xml(child_elem, handle)
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)
def from_xml(self, elem, handle=None): """Method updates/fills the object from the xml representation of the external method object. """ self._handle = handle if elem.attrib: for attr_name, attr_value in ucscgenutils.iteritems( elem.attrib): if attr_name in self.__property_map: attr = self.__property_map[attr_name] method_prop_meta = self.__property_meta[attr] if method_prop_meta.inp_out == "Input" or ( method_prop_meta.is_complex_type): continue self.set_attr(attr, str(attr_value)) elif attr_name in ExternalMethod._external_method_attrs: self.set_attr( ExternalMethod._external_method_attrs[attr_name], str(attr_value)) child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not ET.iselement(child_elem): continue child_name = child_elem.tag if child_name in self.__property_map: child_name = self.__property_map[child_name] method_prop_meta = self.__property_meta[ child_name] if method_prop_meta.inp_out == "Output" and \ (method_prop_meta.is_complex_type): child_obj = ucsccoreutils.get_ucsc_obj( method_prop_meta.field_type, child_elem) if child_obj is not None: self.set_attr(child_name, child_obj) child_obj.from_xml(child_elem, handle)
def from_xml(self, elem, handle=None): """ Method updates the object from the xml representation of the managed object. """ self._handle = handle if elem.attrib: if self.__class__.__name__ != "ManagedObject": for attr_name, attr_value in imcgenutils.iteritems(elem.attrib): if imccoreutils.property_exists_in_prop_map(self, attr_name): attr_name = \ imccoreutils.get_property_from_prop_map(self, attr_name) else: self.__xtra_props[attr_name] = _GenericProp( attr_name, attr_value, False) object.__setattr__(self, attr_name, attr_value) else: for attr_name, attr_value in imcgenutils.iteritems(elem.attrib): object.__setattr__(self, attr_name, attr_value) if hasattr(self, 'rn') and not hasattr(self, 'dn'): self._dn_set() elif not hasattr(self, 'rn') and hasattr(self, 'dn'): self.__set_prop("rn", os.path.basename(self.dn), forced=True) self.mark_clean() child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not ET.iselement(child_elem): continue if self.__class__.__name__ != "ManagedObject": mo_meta = imccoreutils.get_mo_meta(self) field_names = mo_meta.field_names if field_names and child_elem.tag in field_names: pass class_id = imcgenutils.word_u(child_elem.tag) child_obj = imccoreutils.get_imc_obj(class_id, child_elem, self) self.child_add(child_obj) child_obj.from_xml(child_elem, handle)
def from_xml(self, elem, handle=None): """ This method is form objects out of xml element. This is called internally from imcxmlcode.from_xml_str method. Example: xml = '<testLsA a="1" b="2" c="3" dn="org-root/" rn=""> <testLsB a="1" b="2" c="3" dn="org-root/" rn="" /></testLsA>'\n obj = xc.from_xml_str(xml)\n print type(obj)\n Outputs: <class 'imcsdk.imcmo.GenericMo'> """ if elem is None: return None self._handle = handle self._class_id = elem.tag if elem.attrib: for name, value in imcgenutils.iteritems(elem.attrib): self.__dict__[name] = value self.__properties[name] = str(value) if self.rn and self.dn: pass elif self.rn and not self.dn: if self.__parent_dn and self.__parent_dn != "": self.dn = self.__parent_dn + '/' + self.rn self.__properties['dn'] = self.dn else: self.dn = self.rn self.__properties['dn'] = self.dn elif not self.rn and self.dn: self.rn = os.path.basename(self.dn) self.__properties['rn'] = self.rn children = elem.getchildren() if children: for child in children: if not ET.iselement(child): continue class_id = imcgenutils.word_u(child.tag) pdn = None if 'dn' in dir(self): pdn = self.dn child_obj = GenericMo(class_id, parent_mo_or_dn=pdn) self.child_add(child_obj) child_obj.from_xml(child, handle)
def from_xml(self, elem, handle=None): """ Method updates the object from the xml representation of the managed object. """ self._handle = handle if elem.attrib: if self.__class__.__name__ != "ManagedObject": for attr_name, attr_value in ucscgenutils.iteritems( elem.attrib): if attr_name in self.prop_map: attr_name = self.prop_map[attr_name] else: self.__xtra_props[attr_name] = _GenericProp( attr_name, attr_value, False) object.__setattr__(self, attr_name, attr_value) else: for attr_name, attr_value in ucscgenutils.iteritems( elem.attrib): object.__setattr__(self, attr_name, attr_value) if hasattr(self, 'rn') and not hasattr(self, 'dn'): self._dn_set() elif not hasattr(self, 'rn') and hasattr(self, 'dn'): self.__set_prop("rn", os.path.basename(self.dn), forced=True) self.mark_clean() child_elems = elem.getchildren() if child_elems: for child_elem in child_elems: if not ET.iselement(child_elem): continue if self.__class__.__name__ != "ManagedObject" and ( child_elem.tag in self.mo_meta.field_names): pass class_id = ucscgenutils.word_u(child_elem.tag) child_obj = ucsccoreutils.get_ucsc_obj(class_id, child_elem, self) self.child_add(child_obj) child_obj.from_xml(child_elem, handle)
def from_xml(self, elem, handle=None): """ This method is form objects out of xml element. This is called internally from ucscxmlcode.from_xml_str method. Example: xml = '<testLsA a="1" b="2" c="3" dn="org-root/" rn=""> <testLsB a="1" b="2" c="3" dn="org-root/" rn="" /></testLsA>'\n obj = xc.from_xml_str(xml)\n print type(obj)\n Outputs: <class 'ucscsdk.ucscmo.GenericMo'> """ if elem is None: return None self._handle = handle self._class_id = elem.tag if elem.attrib: for name, value in ucscgenutils.iteritems(elem.attrib): self.__dict__[name] = value self.__properties[name] = str(value) if self.rn and self.dn: pass elif self.rn and not self.dn: if self.__parent_dn is not None and self.__parent_dn != "": self.dn = self.__parent_dn + '/' + self.rn self.__properties['dn'] = self.dn else: self.dn = self.rn self.__properties['dn'] = self.dn elif not self.rn and self.dn: self.rn = os.path.basename(self.dn) self.__properties['rn'] = self.rn # else: # raise ValueError("Both rn and dn does not present.") children = elem.getchildren() if children: for child in children: if not ET.iselement(child): continue class_id = ucscgenutils.word_u(child.tag) pdn = None if 'dn' in dir(self): pdn = self.dn child_obj = GenericMo(class_id, parent_mo_or_dn=pdn) self.child_add(child_obj) child_obj.from_xml(child, handle)
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