当前位置: 首页>>代码示例>>Python>>正文


Python ElementTree.find方法代码示例

本文整理汇总了Python中xml.etree.ElementTree.find方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.find方法的具体用法?Python ElementTree.find怎么用?Python ElementTree.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xml.etree.ElementTree的用法示例。


在下文中一共展示了ElementTree.find方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
 def __init__(self):
     self.unitTechs = []
     self.buildingTechs = []
     self.mothershipTechs = []
     tree = ElementTree(file="TechTree.xml")
     units = tree.find("Units")
     for u in units.findall("Tech"):
         self.unitTechs.append(Tech(self, u))
     buildings = tree.find("Buildings")
     for b in buildings.findall("Tech"):
         self.buildingTechs.append(Tech(self, b))
     motherships = tree.find("Mothership")
     for m in motherships.findall("Tech"):
         self.mothershipTechs.append(Tech(self, m))
开发者ID:TyMarc,项目名称:Orion-avec-cheveux,代码行数:16,代码来源:TechTree.py

示例2: set_game_info

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
 def set_game_info(self, info):
     self.info = info
     tree = ElementTree()
     tree.parse(info["path"])
     link_node = tree.find("link")
     if link_node is not None:
         self.link_field.set_text(link_node.text.strip())
     else:
         self.link_field.set_text("")
开发者ID:F1relight,项目名称:fs-uae-debian,代码行数:11,代码来源:PickGameDialog.py

示例3: setChannel

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
def setChannel(androidManifestFilePath,channel):
    '''
    修改AndroidManifest.xml中的UMENG_CHANNEL
    '''
    if not os.path.exists(androidManifestFilePath):
        sys.exit(androidManifestFilePath+' 不存在')

    xml.etree.ElementTree.register_namespace("android","http://schemas.android.com/apk/res/android")
    tree = ElementTree()   
    xmlRoot=tree.parse(androidManifestFilePath)
    channelNode=tree.find("./application/meta-data[@{http://schemas.android.com/apk/res/android}name='UMENG_CHANNEL']")
    channelNode.set("{http://schemas.android.com/apk/res/android}value",channel)
    tree.write(androidManifestFilePath, "UTF-8", True)
开发者ID:jinshiyi11,项目名称:AppBuilder,代码行数:15,代码来源:UMengChannelPacker.py

示例4: parse_user_details

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
def parse_user_details(s):
    """Takes a string XML representation of a user's details and
    returns a dictionary of values we care about"""
    root = ET.find('./user')
    if not root:
        print 'aaaargh'
        return None
    user = {
        'id': root.attrib['id'],
        'username': root.attrib['display_name']
    }
    try:
        user['lat'] = float(root.find('./home').attrib['lat'])
        user['lon'] = float(root.find('./home').attrib['lon'])
    except AttributeError:
        pass
    user['changesets'] = int(root.find('./changesets').attrib['count'])
    return user
开发者ID:ebrelsford,项目名称:maproulette,代码行数:20,代码来源:helpers.py

示例5: ConfigXmlWriter

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
class ConfigXmlWriter(RcbXmlReaderWriter):

	def __init__(self, createNew):

		Logutil.log('init ConfigXmlWriter', util.LOG_LEVEL_INFO)

		self.createNew = createNew

		if(createNew):
			configFile = os.path.join(util.getAddonInstallPath(), 'resources', 'database', 'config_template.xml')
		else:
			configFile = util.getConfigXmlPath()

		if(not os.path.isfile(configFile)):
			Logutil.log('File config.xml does not exist. Place a valid config file here: ' + str(configFile), util.LOG_LEVEL_ERROR)
		else:
			self.tree = ElementTree().parse(configFile)

	""" Functions for generating XML objects from objects """
	def getXmlAttributesForRomCollection(self, rc):
		return {'id': str(rc.id), 'name': rc.name}

	def getXmlElementsForRomCollection(self, rc):
		elements = []
		# String attributes
		for e in ['gameclient', 'emulatorCmd', 'emulatorParams', 'preCmd', 'postCmd',
				  'saveStatePath', 'saveStateParams']:
			try:
				el = Element(e, {})
				el.text = getattr(rc, e)
				elements.append(el)
			except AttributeError as exc:
				# Skip any errors
				pass

		# Non-string attributes
		for e in ['useBuiltinEmulator', 'useEmuSolo', 'usePopen', 'ignoreOnScan', 'allowUpdate', 'autoplayVideoMain',
				  'autoplayVideoInfo', 'useFoldernameAsGamename', 'maxFolderDepth', 'doNotExtractZipFiles',
				  'makeLocalCopy', 'diskPrefix']:
			try:
				el = Element(e, {})
				el.text = str(getattr(rc, e))
				elements.append(el)
			except AttributeError as exc:
				# Skip any errors
				pass

		for romPath in rc.romPaths:
			el = Element('romPath', {})
			el.text = romPath
			elements.append(el)

		return elements

	def getXmlAttributesForSite(self, site):
		attrs = {'name': site.name, 'path': site.path}
		return attrs

	def getXmlElementsForSite(self, site):
		""" Not needed """
		pass

	def writeRomCollections(self, romCollections, isEdit):

		Logutil.log('write Rom Collections', util.LOG_LEVEL_INFO)

		romCollectionsXml = self.tree.find('RomCollections')

		#HACK: remove all Rom Collections and create new
		if(isEdit):
			for romCollectionXml in romCollectionsXml.findall('RomCollection'):
				romCollectionsXml.remove(romCollectionXml)


		for romCollection in romCollections.values():

			Logutil.log('write Rom Collection: ' + str(romCollection.name), util.LOG_LEVEL_INFO)

			romCollectionXml = SubElement(romCollectionsXml, 'RomCollection', self.getXmlAttributesForRomCollection(romCollection))

			for subel in self.getXmlElementsForRomCollection(romCollection):
				romCollectionXml.append(subel)


			for mediaPath in romCollection.mediaPaths:

				success, message = self.searchConfigObjects('FileTypes/FileType', mediaPath.fileType.name, 'FileType')
				if(not success):
					return False, message

				SubElement(romCollectionXml, 'mediaPath', {'type': mediaPath.fileType.name}).text = mediaPath.path

			#image placing
			if(not self.createNew):
				#in case of an update we have to create new options
				if(romCollection.name == 'MAME' and not self.createNew):
					self.addFileTypesForMame()
					self.addImagePlacingForMame()

			if(romCollection.imagePlacingMain != None and romCollection.imagePlacingMain.name != ''):
#.........这里部分代码省略.........
开发者ID:bruny,项目名称:romcollectionbrowser,代码行数:103,代码来源:configxmlwriter.py

示例6: __init__

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
class ConfigXmlWriter:
	
	def __init__(self, createNew):
		
		Logutil.log('init ConfigXmlWriter', util.LOG_LEVEL_INFO)
		
		self.createNew = createNew
		
		if(createNew):
			configFile = os.path.join(util.getAddonInstallPath(), 'resources', 'database', 'config_template.xml')
		else:
			configFile = util.getConfigXmlPath()
		
		if(not os.path.isfile(configFile)):
			Logutil.log('File config.xml does not exist. Place a valid config file here: ' +str(configFile), util.LOG_LEVEL_ERROR)
			return False, util.localize(32003)
		
		self.tree = ElementTree().parse(configFile)
	
	
	def writeRomCollections(self, romCollections, isEdit):
				
		Logutil.log('write Rom Collections', util.LOG_LEVEL_INFO)
				
		romCollectionsXml = self.tree.find('RomCollections')
		
		#HACK: remove all Rom Collections and create new
		if(isEdit):
			for romCollectionXml in romCollectionsXml.findall('RomCollection'):				
				romCollectionsXml.remove(romCollectionXml)
				
		
		for romCollection in romCollections.values():
			
			Logutil.log('write Rom Collection: ' +str(romCollection.name), util.LOG_LEVEL_INFO)
			
			romCollectionXml = SubElement(romCollectionsXml, 'RomCollection', {'id' : str(romCollection.id), 'name' : romCollection.name})
			SubElement(romCollectionXml, 'useBuiltinEmulator').text = str(romCollection.useBuiltinEmulator)
			SubElement(romCollectionXml, 'gameclient').text = romCollection.gameclient
			SubElement(romCollectionXml, 'emulatorCmd').text = romCollection.emulatorCmd
			SubElement(romCollectionXml, 'emulatorParams').text = romCollection.emulatorParams
			
			for romPath in romCollection.romPaths:
				SubElement(romCollectionXml, 'romPath').text = romPath
							
			SubElement(romCollectionXml, 'saveStatePath').text = romCollection.saveStatePath
			SubElement(romCollectionXml, 'saveStateParams').text = romCollection.saveStateParams
				
			for mediaPath in romCollection.mediaPaths:
				
				success, message = self.searchConfigObjects('FileTypes/FileType', mediaPath.fileType.name, 'FileType')
				if(not success):
					return False, message								
												
				SubElement(romCollectionXml, 'mediaPath', {'type' : mediaPath.fileType.name}).text = mediaPath.path
				
			SubElement(romCollectionXml, 'preCmd').text = romCollection.preCmd
			SubElement(romCollectionXml, 'postCmd').text = romCollection.postCmd
			SubElement(romCollectionXml, 'useEmuSolo').text = str(romCollection.useEmuSolo)
			SubElement(romCollectionXml, 'usePopen').text = str(romCollection.usePopen)
			SubElement(romCollectionXml, 'ignoreOnScan').text = str(romCollection.ignoreOnScan)
			SubElement(romCollectionXml, 'allowUpdate').text = str(romCollection.allowUpdate)
			SubElement(romCollectionXml, 'autoplayVideoMain').text = str(romCollection.autoplayVideoMain)
			SubElement(romCollectionXml, 'autoplayVideoInfo').text = str(romCollection.autoplayVideoInfo)
			SubElement(romCollectionXml, 'useFoldernameAsGamename').text = str(romCollection.useFoldernameAsGamename)
			SubElement(romCollectionXml, 'maxFolderDepth').text = str(romCollection.maxFolderDepth)
			SubElement(romCollectionXml, 'doNotExtractZipFiles').text = str(romCollection.doNotExtractZipFiles)
			SubElement(romCollectionXml, 'diskPrefix').text = str(romCollection.diskPrefix)
			
			if (os.environ.get( "OS", "xbox" ) == "xbox"):
				SubElement(romCollectionXml, 'xboxCreateShortcut').text = str(romCollection.xboxCreateShortcut)
				SubElement(romCollectionXml, 'xboxCreateShortcutAddRomfile').text = str(romCollection.xboxCreateShortcutAddRomfile)
				SubElement(romCollectionXml, 'xboxCreateShortcutUseShortGamename').text = str(romCollection.xboxCreateShortcutUseShortGamename)
				
			#image placing
			if(not self.createNew):
				#in case of an update we have to create new options
				if(romCollection.name == 'MAME' and not self.createNew):
					self.addFileTypesForMame()
					self.addImagePlacingForMame()
					
			if(romCollection.imagePlacingMain != None and romCollection.imagePlacingMain.name != ''):
				success, message = self.searchConfigObjects('ImagePlacing/fileTypeFor', romCollection.imagePlacingMain.name, 'ImagePlacing')
				if(not success):
					return False, message
				SubElement(romCollectionXml, 'imagePlacingMain').text = romCollection.imagePlacingMain.name 
			else:
				SubElement(romCollectionXml, 'imagePlacingMain').text = 'gameinfobig'
				
			if(romCollection.imagePlacingInfo != None and romCollection.imagePlacingInfo.name != ''):
				success, message = self.searchConfigObjects('ImagePlacing/fileTypeFor', romCollection.imagePlacingInfo.name, 'ImagePlacing')
				if(not success):
					return False, message
				SubElement(romCollectionXml, 'imagePlacingInfo').text = romCollection.imagePlacingInfo.name 
			else:
				SubElement(romCollectionXml, 'imagePlacingInfo').text = 'gameinfosmall'
			
			if(romCollection.scraperSites == None or len(romCollection.scraperSites) == 0):
				SubElement(romCollectionXml, 'scraper', {'name' : 'thegamesdb.net', 'replaceKeyString' : '', 'replaceValueString' : ''})
				SubElement(romCollectionXml, 'scraper', {'name' : 'archive.vg', 'replaceKeyString' : '', 'replaceValueString' : ''})
#.........这里部分代码省略.........
开发者ID:ProfessorKaos64,项目名称:RetroRig,代码行数:103,代码来源:configxmlwriter.py

示例7: makeContent

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
def makeContent(pages,media,p,tdir):
    pf=p['href']
    if debugMode():
        print("makeContent",pf)

    if pf==None:
        return False

    # strip off id references in path
    pp = pf.find("#")
    if pp>-1:
        f = pf[0:pp]
    else:
        f = pf
        
    # can we use extensions?
    extf = get_extensions()

    ff = os.path.normpath(tdir + os.sep + f)
    tree = ElementTree()
    tree.parse(ff)
                
    body = tree.find("body")

    if body==None:
        print("Error: no body in",f)
        return False

    # erase topic title line
    bh1 = body.find("h1")
    if bh1!=None:
        body.remove(bh1)
    
    # get a list of all the keywords in the file
    key_list = []
    head = tree.find("head")
    if head==None:
        print("Error: no head in",f)
        return False
    
    # init field info
    fieldlist = {}
    
    # make a list of all <meta> elements and then find
    # the keywords in DC.subject.
    metas = head.findall("meta")
    for meta in metas:
        mname = meta.get("name")
        
        if mname!=None and mname=="DC.subject":
            DCcontent = meta.get("content")
            if DCcontent!=None:
                content_tags = DCcontent.split(",")
                for ctag in content_tags:
                    ctag = ctag.strip()
                    if not ctag in key_list:
                        key_list.append(ctag)
                        # add tag to global tag list
                        if not ctag in get_tag_list():
                            add_tag(ctag)
                            # if we can, add this tag to the vocabulary
                            if extf and get_tagflag():
                                vcab = get_vocabulary()
                                addVocabularyTerm(vcab,ctag)
                                print(" add",vcab,"term",ctag)
                                
        # look for fields provided in the input
        # this is a local extension
        elif mname!=None and mname.startswith("FIELD."):
            fpos = mname.find(".")
            fieldname = mname[fpos+1:]
            fieldvalue = meta.get("content")
            if debugMode():
              print("field: ",fieldname,fieldvalue)
            fieldlist[fieldname] = fieldvalue
                
                            
    # store the tags (keywords)
    p['keywords'] = key_list

    if len(fieldlist)>0:
        p['fields'] = fieldlist
        
    if debugMode():
        print("key_list",key_list)
        print(get_tag_list())
        
    # get a list of parentlinks and remove them
    if get_sourcetype()=="DITAXHTML":
      plinks = []
      removeParentTopicLinks(body, plinks,1)
 
            
    # if not doing outline processing for DITA content,
    # move DITA parent links to top
    if not get_outline() and get_sourcetype()=="DITAXHTML":
      if len(plinks)>0:
          # move deleted parent links to the top
          for plink in plinks:
              body.insert(0,plink)
#.........这里部分代码省略.........
开发者ID:rjohnson8103,项目名称:WParchive,代码行数:103,代码来源:ditapub.py

示例8: parse_document

# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import find [as 别名]
	def parse_document(self, etree, systemdate):
		query_queue = collections.defaultdict(list)

		systemdate_sqlite_str = systemdate.strftime('%Y-%m-%d %H:%M:%S.%f')


		snapshot_utc_date = datetime.datetime.utcfromtimestamp(
				int(etree.find('PinnacleFeedTime').text) / 1e3
		)
		snapshot_sqlite_str = snapshot_utc_date.strftime('%Y-%m-%d %H:%M:%S.%f')
		for event_el in etree.findall('events/event'):
			islive = coalesce(event_el, 'IsLive', 1)
			eventid = event_el.find('gamenumber').text
			is_contest = len(event_el.findall('contest_maximum')) != 0
			evdate_str = event_el.find('event_datetimeGMT').text
			evdate_dt = datetime.datetime.strptime(evdate_str, '%Y-%m-%d %H:%M')
# For unknown reasons, pinnacle's xml lists some matches as starting on weird
# times like 19:59 and 21:44. This will fix this.
			if evdate_dt.minute % 5 == 4:
				LOGGER.debug('Adding 1 minute to datetime: %s', evdate_dt)
				evdate_dt += datetime.timedelta(minutes = 1)

			def add_args(*args, **kwargs):
				if args[0] == 'odds':
					query_queue[eventid].append([
								BEFORE_SQL,
								[ kwargs['periodnumber'],
								kwargs['type'],
								kwargs['eventid']]
					])
				args_to_append = cl.get_insert_args_mysql(*args, **kwargs)
				query_queue[eventid].append(args_to_append)
				if args[0] == 'odds':
					query_queue[eventid].append([
								AFTER_SQL1,
								[ kwargs['periodnumber'],
								kwargs['type'],
								kwargs['eventid']]
					])
					query_queue[eventid].append([
								AFTER_SQL2,
								[ kwargs['periodnumber'],
								kwargs['type'],
								kwargs['eventid']]
					])

			add_args(
				'events',
				'replace',
				id = eventid,
				date = cl.datetime_to_sqlite_str(evdate_dt),
				sporttype = event_el.find('sporttype').text,
				league = event_el.find('league').text,
				islive = (1 if islive == 'Yes' else 0),
				description = coalesce(event_el, 'description', 1),
			)
			for participant_el in event_el.findall('participants/participant'):
				contestantnum = participant_el.find('contestantnum').text
				rotnum = participant_el.find('rotnum').text
				vhd = coalesce(participant_el, 'visiting_home_draw', 1)
				pitcher = coalesce(participant_el, 'pitcher', 1)
				add_args(
					'participants',
					'replace',
					eventid = eventid,
					contestantnum = contestantnum,
					rotnum = rotnum,
					vhdou = VHDOU_VAL[vhd],
					pitcher = pitcher,	
					name = participant_el.find('participant_name').text,
				)
				if is_contest:
					add_args(
						'snapshots',
						'replace',
						eventid = eventid,
						date = snapshot_sqlite_str,
						systemdate = systemdate_sqlite_str,
						mlmax = int(coalesce(event_el, 'contest_maximum', 1)),
					)
					add_args(
						'odds',
						'replace',
						eventid = eventid,
						periodnumber = None,
						snapshotdate = snapshot_sqlite_str,
						type = 'm',
						threshold = 0,
						vhdou = None,
						price = dec_odds(
							coalesce(
								participant_el, 'odds/moneyline_value', 1
							)
						),
						to_base = fix_to_base(coalesce(
									participant_el, 'odds/to_base', 1
						)),
						contestantnum = contestantnum,
						rotnum = rotnum,

#.........这里部分代码省略.........
开发者ID:gtzampanakis,项目名称:statsfair,代码行数:103,代码来源:pinnacle_download.py


注:本文中的xml.etree.ElementTree.find方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。