我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.cElementTree.parse()。
def pull_item(self, index): img_id = self.ids[index] target = ET.parse(self._annopath % img_id).getroot() img = cv2.imread(self._imgpath % img_id) height, width, channels = img.shape if self.target_transform is not None: target = self.target_transform(target, width, height) if self.transform is not None: target = np.array(target) img, boxes, labels = self.transform(img, target[:, :4], target[:, 4]) # to rgb img = img[:, :, (2, 1, 0)] # img = img.transpose(2, 0, 1) target = np.hstack((boxes, np.expand_dims(labels, axis=1))) return torch.from_numpy(img).permute(2, 0, 1), target, height, width # return torch.from_numpy(img), target, height, width
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'softPkg' rootClass = softPkg rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'devicepkg' rootClass = devicepkg rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'deviceconfiguration' rootClass = deviceconfiguration rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'domainmanagerconfiguration' rootClass = domainmanagerconfiguration rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'profile' rootClass = profile rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'softwareassembly' rootClass = softwareassembly rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'softwarecomponent' rootClass = softwarecomponent rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(inFileName): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'properties' rootClass = properties rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None ## sys.stdout.write('<?xml version="1.0" ?>\n') ## rootObj.export(sys.stdout, 0, name_=rootTag, ## namespacedef_='', ## pretty_print=True) return rootObj
def parse(stream): """Parse a stream containing XML into an ``InputDefinition``. :param stream: stream containing XML to parse. :return: definition: an ``InputDefinition`` object. """ definition = InputDefinition() # parse XML from the stream, then get the root node root = ET.parse(stream).getroot() for node in root: if node.tag == "configuration": # get config for each stanza definition.inputs = parse_xml_data(node, "stanza") else: definition.metadata[node.tag] = node.text return definition
def parse_rec(filename): """ Parse a PASCAL VOC xml file """ tree = ET.parse(filename) objects = [] for obj in tree.findall('object'): obj_struct = {} obj_struct['name'] = obj.find('name').text obj_struct['pose'] = obj.find('pose').text obj_struct['truncated'] = int(obj.find('truncated').text) obj_struct['difficult'] = int(obj.find('difficult').text) bbox = obj.find('bndbox') obj_struct['bbox'] = [int(bbox.find('xmin').text) - 1, int(bbox.find('ymin').text) - 1, int(bbox.find('xmax').text) - 1, int(bbox.find('ymax').text) - 1] objects.append(obj_struct) return objects
def pull_anno(self, index): '''Returns the original annotation of image at index Note: not using self.__getitem__(), as any transformations passed in could mess up this functionality. Argument: index (int): index of img to get annotation of Return: list: [img_id, [(label, bbox coords),...]] eg: ('001718', [('dog', (96, 13, 438, 332))]) ''' img_id = self.ids[index] anno = ET.parse(self._annopath % img_id).getroot() gt = self.target_transform(anno, 1, 1) return img_id[1], gt
def loadXML(self): print "[Volume Adjust] load xml..." if not os_path.exists(self.filename): return self.read_services=[] self.read_volume=[] try: tree = ci_parse(self.filename).getroot() for channels in tree.findall("channels"): for service in channels.findall("service"): read_service_name = service.get("name").encode("UTF-8") read_service_ref = service.get("ref").encode("UTF-8") read_service_volume = service.get("volume").encode("UTF-8") self.read_services.append (read_service_ref) self.read_volume.append (read_service_volume) except: print "[Volume Adjust] error parsing xml..." for item in self.read_services: if len(item): self.finishedChannelSelection(item) self["ServiceList"].l.setList(self.servicelist)
def loadXML(self): # load the list print "[Volume Adjust] load xml..." if not os_path.exists(self.filen): return self.read_services=[] self.read_volume=[] try: tree = ci_parse(self.filen).getroot() for channels in tree.findall("channels"): for service in channels.findall("service"): read_service_name = service.get("name").encode("UTF-8") read_service_ref = service.get("ref").encode("UTF-8") read_service_volume = service.get("volume").encode("UTF-8") self.read_services.append (read_service_ref) self.read_volume.append (read_service_volume) except: print "[Volume Adjust] error parsing xml..." for i in self.read_services: print i
def _le_xml(self, arquivo): if arquivo is None: return False if not isinstance(arquivo, basestring): arquivo = etree.tounicode(arquivo) if arquivo is not None: if isinstance(arquivo, basestring): if NAMESPACE_NFSE in arquivo: arquivo = por_acentos(arquivo) if u'<' in arquivo: self._xml = etree.fromstring(tira_abertura(arquivo)) else: arq = open(arquivo) txt = ''.join(arq.readlines()) txt = tira_abertura(txt) arq.close() self._xml = etree.fromstring(txt) else: self._xml = etree.parse(arquivo) return True return False
def validar(self): arquivo_esquema = self.caminho_esquema + self.arquivo_esquema # Aqui é importante remover a declaração do encoding # para evitar erros de conversão unicode para ascii xml = tira_abertura(self.xml).encode(u'utf-8') esquema = etree.XMLSchema(etree.parse(arquivo_esquema)) if not esquema.validate(etree.fromstring(xml)): for e in esquema.error_log: if e.level == 1: self.alertas.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', '')) elif e.level == 2: self.erros.append(e.message.replace('{http://www.portalfiscal.inf.br/nfe}', '')) return esquema.error_log
def read(filename, createTree=True): doc = etree.parse(filename) root = doc.getroot() root.get('name') root.get('StandardName') tolower(root) rootNode = root.find('./robotnode[@name="%s"]' % root.get('RootNode')) return parse(rootNode, root) # if __name__ == "__main__": # import sys, pprint # print(sys.argv[1]) # structure = read(sys.argv[1],False) # pprint.pprint(structure) # pass
def __parse_annotation(self, element): truncated = _findNode(element, 'truncated', parse=int) difficult = _findNode(element, 'difficult', parse=int) class_name = _findNode(element, 'name').text if class_name not in self.classes: raise ValueError('class name \'{}\' not found in classes: {}'.format(class_name, list(self.classes.keys()))) box = np.zeros((1, 5)) box[0, 4] = self.name_to_label(class_name) bndbox = _findNode(element, 'bndbox') box[0, 0] = _findNode(bndbox, 'xmin', 'bndbox.xmin', parse=float) - 1 box[0, 1] = _findNode(bndbox, 'ymin', 'bndbox.ymin', parse=float) - 1 box[0, 2] = _findNode(bndbox, 'xmax', 'bndbox.xmax', parse=float) - 1 box[0, 3] = _findNode(bndbox, 'ymax', 'bndbox.ymax', parse=float) - 1 return truncated, difficult, box
def __parse_annotations(self, xml_root): size_node = _findNode(xml_root, 'size') width = _findNode(size_node, 'width', 'size.width', parse=float) height = _findNode(size_node, 'height', 'size.height', parse=float) boxes = np.zeros((0, 5)) for i, element in enumerate(xml_root.iter('object')): try: truncated, difficult, box = self.__parse_annotation(element) except ValueError as e: raise_from(ValueError('could not parse object #{}: {}'.format(i, e)), None) if truncated and self.skip_truncated: continue if difficult and self.skip_difficult: continue boxes = np.append(boxes, box, axis=0) return boxes
def cve_parse(self): """ Resolve the latest rules,parse new rule from cve.xml :return: None """ cve_file = self.get_cve_file() if not isinstance(cve_file, list): tree = self.parse_xml(cve_file) root = tree.getroot() childs = root.findall('.//%sentry' % self.NS) for child in childs: # child is entry Element cve_id = child.attrib['id'] cve_info = self.cve_info(child) if len(cve_info) != 0: self._result[cve_id] = cve_info else: for filename in cve_file: tree = self.parse_xml(filename) root = tree.getroot() childs = root.findall('.//%sentry' % self.NS) for child in childs: # child is entry Element cve_id = child.attrib['id'] cve_info = self.cve_info(child) if len(cve_info) != 0: self._result[cve_id] = cve_info
def checkMagic(self, file_name_fullpath): # As long as we find one Appcompat PersistenceType we're declaring it good for us # Check magic magic_id = self.id_filename(file_name_fullpath) if 'XML' in magic_id: file_object = loadFile(file_name_fullpath) try: root = etree.parse(file_object).getroot() # todo: replace findall with find for reg_key in root.findall('PersistenceItem'): if reg_key.find('PersistenceType').text.lower() == "Appcompat".lower(): return True except Exception: logger.warning("[%s] Failed to parse XML for: %s" % (self.ingest_type, file_name_fullpath)) return False
def checkMagic(self, file_name_fullpath): # Check magic magic_id = self.id_filename(file_name_fullpath) if 'XML' in magic_id: file_object = loadFile(file_name_fullpath) try: # todo: Issue documents are declared as UTF-8 but not encoded as such, etree may fail to parse them # root = etree.parse(file_object).getroot() # if root.tag == 'IssueList': return True if 'IssueList' in magic_id or 'batchresult' in magic_id: return True except Exception as e: logger.exception("[%s] Failed to parse XML for: %s" % (self.ingest_type, file_name_fullpath)) finally: file_object.close() return False
def checkMagic(self, file_name_fullpath): # As long as we find one Appcompat PersistenceType we're declaring it good for us # Check magic magic_id = self.id_filename(file_name_fullpath) if 'XML' in magic_id: file_object = loadFile(file_name_fullpath) try: root = etree.parse(file_object).getroot() # todo: replace findall with find: for reg_key in root.findall('AppCompatItemExtended'): if reg_key.find('PersistenceType').text.lower() == "Appcompat".lower(): return True except Exception: logger.warning("[%s] Failed to parse XML for: %s" % (self.ingest_type, file_name_fullpath)) finally: file_object.close() return False
def max_shard_size_united(self): et = None max_shard_size = DEFAULT_SHARD_SIZE try: et = ET.parse(CONFIG_FILE) max_shard_size_sterile = None for tags in et.iter(str("custom_max_shard_size_enabled")): if int(tags.text) == 1: for tags2 in et.iter(str("max_shard_size")): max_shard_size_sterile = int(tags2.text) max_shard_size = max_shard_size_sterile else: max_shard_size = DEFAULT_SHARD_SIZE except Exception as e: logger.error("Unspecified XML parse error" + str(e)) return (max_shard_size)
def max_shard_size_unit(self): et = None shard_size_unit = 1 try: et = ET.parse(CONFIG_FILE) max_shard_size_sterile = None for tags in et.iter(str("custom_max_shard_size_enabled")): if int(tags.text) == 1: for tags3 in et.iter(str("shard_size_unit")): shard_size_unit = int(tags3.text) except Exception as e: logger.error("Unspecified XML parse error" + str(e)) return (shard_size_unit)
def if_logged_in(self): """Return True if user has already logged in with these credentials""" logged_in = '0' try: et = ET.parse('storj_account_conf.xml') for tags in et.iter('logged_in'): logged_in = tags.text except IOError: self.__logger.error('Error in Account Manager login') self.__logger.error('Function: if_logged_in') self.__logger.error('Credentials file not existing') return False return logged_in == '1'
def process_file(tcxfile, lever): """ Process the whole TCX file. """ tree = etree.parse(tcxfile) root = tree.getroot() tracks = [] for element in root.iter(): if element.tag == '{%s}Track'%ns1: tracks.append(element) for element in tracks: process_track(element, lever) new_name = "vpower_" + tcxfile tree.write(new_name, encoding='utf-8', xml_declaration=True)
def pull_item(self, index): img_id = self.ids[index] target = ET.parse(self._annopath % img_id).getroot() img = cv2.imread(self._imgpath % img_id) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # img = imread(self._imgpath % img_id) height, width, channels = img.shape if self.target_transform is not None: target = self.target_transform(target, width, height) if self.transform is not None: target = np.array(target) img, boxes, labels = self.transform(img, target[:, :4], target[:, 4]) # to rgb img = img[:, :, (2, 1, 0)] # img = img.transpose(2, 0, 1) target = np.hstack((boxes, np.expand_dims(labels, axis=1))) # i commented this uncomment for the pytorch_eval # return torch.from_numpy(img).permute(2, 0, 1), target, height, width return img, target, height, width # return torch.from_numpy(img), target, height, width # IDK WTF
def parse(inFileName, silence=False): doc = parsexml_(inFileName) rootNode = doc.getroot() rootTag, rootClass = get_root_tag(rootNode) if rootClass is None: rootTag = 'entry' rootClass = entry rootObj = rootClass.factory() rootObj.build(rootNode) # Enable Python to collect the space used by the DOM. doc = None if not silence: sys.stdout.write('<?xml version="1.0" ?>\n') rootObj.export( sys.stdout, 0, name_=rootTag, namespacedef_='', pretty_print=True) return rootObj
def parse_xdmf(xml_file): tree = ET.parse(xml_file) root = tree.getroot() dsets = [] timestamps = [] for i, step in enumerate(root[0][0]): if step.tag == "Time": # Support for earlier dolfin formats timestamps = [float(time) for time in step[0].text.strip().split(" ")] elif step.tag == "Grid": timestamp = None dset_address = None for prop in step: if prop.tag == "Time": timestamp = float(prop.attrib["Value"]) elif prop.tag == "Attribute": dset_address = prop[0].text.split(":")[1] if timestamp is None: timestamp = timestamps[i-1] dsets.append((timestamp, dset_address)) return dsets
def testCode(): #------------------------------------------------------------------ dic = {} dic["pepe"] = "pepe" lista = [] lista.append("one thing") lista.append("other thing") dic["lista"] = lista xml = XMLCreator() node = xml.createXMLNode("principal_node", dic) ser = xml.serialize(node) print(ser) #------------------------------------------------------------------ #~ xml=XMLCreator() #~ dic=xml.readAll("filename") #~ print(dic) #------------------------------------------------------------------ #~ xml=XMLCreator() #~ data=open("test.xml","r").read() #~ dic=xml.parse(data) #~ print(dic) #***********************TEST***************************
def _parse(self, xml_file): if xml_file: data = ET.parse(xml_file).getroot() else: self.log.error("Failed to retrieve suppliers") return False ''' Data is an XML ElementTree Object ''' self.id_map = {} self.catid = '' self.catname = '' for elem in data.iter('SupplierMapping'): self.mfrid = elem.attrib['supplier_id'] self.mfrname = elem.attrib['name'] if not self.mfrname: self.mfrname = "Unknown" self.id_map[self.mfrid] = self.mfrname self.log.info("Parsed {} Manufacturers from IceCat Supplier Map".format(str(len(self.id_map.keys()))))