• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python dom.getElementsByTagName函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中xml.dom.getElementsByTagName函数的典型用法代码示例。如果您正苦于以下问题:Python getElementsByTagName函数的具体用法?Python getElementsByTagName怎么用?Python getElementsByTagName使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: __init__

    def __init__(self, parent, dom):
        super(Interface, self).__init__(parent, dom)

        # build lists of requests, etc., in this interface
        self.requests = build_list(self, Request,
                                  dom.getElementsByTagName('request'))
        self.events = build_list(self, Event,
                                  dom.getElementsByTagName('event'))
        self.enums = build_list(self, Enum,
                                  dom.getElementsByTagName('enum'))
开发者ID:jonnylamb,项目名称:wayland-docs,代码行数:10,代码来源:protocolparser.py


示例2: load_from_xml

    def load_from_xml(self, dom):
        for tagname in STYLE_TAGS:
            for style in dom.getElementsByTagName(tagname):
                if style.nodeType == xml.dom.Node.ELEMENT_NODE:
                    styleobj = OdtStyle(style)
                    self.__styles[styleobj.name] = styleobj

        for tagname in FONT_TAGS:
            for font in dom.getElementsByTagName(tagname):
                if font.nodeType == xml.dom.Node.ELEMENT_NODE:
                    fontobj = Font(font)
                    self.__fonts[fontobj.name] = fontobj
开发者ID:groboclown,项目名称:py-book-selfpub,代码行数:12,代码来源:odt.py


示例3: DetermineMDType

def DetermineMDType(RawXMLFile):
    '''
    A series of tests is performed to determine the format of the metadata record (these tests look at the structure and content
    of the xml for characteristics unique to certain formatting).
    '''    
    dom = minidom.parse(RawXMLFile)
    XMLElements = [node.tagName for node in dom.getElementsByTagName("*")]
    arcpy.AddMessage("A series of tests will now be performed to determine the current format of the metadata record... \n")
    
#Check 1. Determine if metadata contains information identifying it as being an Arc10 style record.
    if "mdStanName" in XMLElements:
        dom = minidom.parse(RawXMLFile)
        mdStanName = dom.getElementsByTagName('mdStanName')[0].firstChild.data
        
        if str(mdStanName) == "ArcGIS Metadata":
            arcpy.AddMessage("The 'mdStanName' element was found in the data layer and contains the value 'ArcGIS Metadata.' This data layer has been determined to have Arc10 style Metadata. \n")
            del dom
            return "Arc10" 
        else: 
            arcpy.AddMessage("The 'mdStanName' element was found in the data layer but did not contain the value 'ArcGIS Metadata.' Subsequent checks will be performed to determine the format of the metadata. \n")
        
    #else: print "The element 'mdStanName' was not found in the XML file. Subsequent checks will be performed to determine the format of the metadata. \n"

#Check 2. Determine if metadata has 1 or more of several elements unique to Arc10 style metadata records.
    KeyElementCheckList = ["idPurp", "idAbs", "idCredit", "searchKeys"]
    KeyElementCounter = 0
    for KeyElement in KeyElementCheckList:
        if KeyElement in XMLElements:
            KeyElementCounter = KeyElementCounter + 1
    if KeyElementCounter > 0:
        arcpy.AddMessage("Out of 4 elements unique to Arc10 style metadata ('idPurp,' idAbs,' idCredit,' and 'searchKeys') " + str(KeyElementCounter) + " were found. This data layer has been determined to have Arc10 style metadata. \n")
        #print "MetadataType Variable = " + MetadataType
        return "Arc10"
   
# else: print "Of 4 elements unique to Arc10 style metadata, none could be found. Subsequent checks will be performed to determine the format of the metadata. \n"
        
#Check 3. Determine if metadata has 1 or more of several elements unique to FGDC style records, in a particular structure.
    try:
        idinfo = dom.getElementsByTagName("idinfo")[0]
        citation = idinfo.getElementsByTagName('citation')[0]
        citeinfo = citation.getElementsByTagName('citeinfo')[0]
        
        metainfo = dom.getElementsByTagName("metainfo")[0]
        metstdn = metainfo.getElementsByTagName("metstdn")[0]
        
        if not citeinfo is None and not metstdn is None:
            arcpy.AddMessage("Based on certain characteristics of the xml, this metadata record has been identified as an FGDC-style record. \n")
            return "FGDC"
        else:
            return "Unknown"
        
    except:
        return "Unknown"
开发者ID:cprice-usgs,项目名称:MDWizard_Source,代码行数:53,代码来源:ExportFGDC_MD_Utility.py


示例4: _ReadXMLFile

    def _ReadXMLFile(self, fname):
        """ Reads in an XML file.
    Args:
      name of file
    Return : (# users added, # users excluded)
      Users are excluded primarily for lack of a "dn" attribute
    """
        f = codecs.open(fname, "r", "utf-8")
        dom = xml.dom.minidom.parseString(f.read())
        users = dom.getElementsByTagName("user")
        added = 0
        excluded = 0
        if len(self.attrs):
            enforceAttrList = True
        else:
            enforceAttrList = False

        for user in users:
            dn, db_user = self._ReadUserXML(user)
            if not dn:
                excluded += 1
            else:
                self._ReadAddUser(dn, db_user, enforceAttrList)
                added += 1
        f.close()
        return (added, excluded)
开发者ID:swapnillipare,项目名称:google-apps-for-your-domain-ldap-sync,代码行数:26,代码来源:userdb.py


示例5: _getGlyphPaths

 def _getGlyphPaths(self, dom):
     symbols = dom.getElementsByTagName('symbol')
     glyphPaths = {}
     for s in symbols:
         pathNode = [p for p in s.childNodes if 'tagName' in dir(p) and p.tagName == 'path']
         glyphPaths[s.getAttribute('id')] = pathNode[0].getAttribute('d')
     return glyphPaths
开发者ID:MatthewASimonson,项目名称:r-orange,代码行数:7,代码来源:redRGGPlot.py


示例6: load

	def load(self):
		d1 = self.dbhelper.dbRead(self.om_db, "xml_date")
		d2 = os.stat(self.defFile).st_mtime
		print "XML_CSL_LOAD", d1, d2
		if d1 != None:
			if d1 > d2:
				# FIXME: hata vermek yerine db'leri sifirlayip yeniden olustur
				print "XML_CSL: OOPS, xml om definition is newer than om db"
				print "XML_CSL: please remove db files manually"
				return
			else:
				return
		print "XML_CSL: creating om DBs..."
		try:
			dom = xml.dom.minidom.parse(self.defFile)
		except:
			print "OMDB: cannot parse '%s'" % (self.defFile)
			return 0
		if dom.documentElement.localName != "comar-om":
			print "OMDB: '%s' is not a COMAR om dtd" % (self.defFile)
			return 0
		ns = dom.getElementsByTagName("namespace")[0]
		# FIXME: namespace in useNS ile ayni oldugunu dogrula
		self.namespace = ns.getAttribute("name")
		print "Adding OM Keys:",
		for node in ns.childNodes:
			self.load_node(node)
			
		dom.unlink()
		if d1 == None:
			self.dbhelper.dbWrite(self.om_db, "xml_date", str(d2))
		return 1
开发者ID:Tayyib,项目名称:uludag,代码行数:32,代码来源:XML_CSL.py


示例7: _parse_gconf_schema

def _parse_gconf_schema(schema_file):
    ret = {}

    dom = xml.dom.minidom.parse(schema_file)
    for gconfschemafile in dom.getElementsByTagName('gconfschemafile'):
        for schemalist in gconfschemafile.getElementsByTagName('schemalist'):
            for schema in schemalist.getElementsByTagName('schema'):
                try:
                    key = schema.getElementsByTagName('applyto')[0].childNodes[0].data
                except IndexError:
                    # huh, no <applyto>? let's use <key>; it has /schemas/
                    # prefix, but it should be clear enough
                    key = schema.getElementsByTagName('key')[0].childNodes[0].data
                    if key.startswith('/schemas/'):
                        key = key[8:]
                type = schema.getElementsByTagName('type')[0].childNodes[0].data
                try:
                    default = schema.getElementsByTagName('default')[0].childNodes[0].data
                    if type == 'bool':
                        if default.lower() == 'true':
                            ret[key] = 'true'
                        else:
                            ret[key] = 'false'
                    else:
                        ret[key] = default
                except IndexError:
                    ret[key] = '' # no gconf default

    return ret
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:29,代码来源:hookutils.py


示例8: __init__

    def __init__(self, file):

        self.fileToAnalise = file

        dom = FromXmlFile(file)
        doc = dom.documentElement

        objs = dom.getElementsByTagName("include")

        for obj in objs:

            temp = string.split(obj.getAttribute("url"), "/")
            inc_file = temp[len(temp) - 1]

            temp1 = string.split(file, "/")

            real_path = ""
            for i in range(0, len(temp1) - 1):
                real_path += "/" + temp1[i]
                # print "real_path="+real_path
            inc_file = str(real_path) + "/" + str(inc_file)
            print "Найден подключаемый файл", inc_file

            dom1 = None
            try:
                doc1 = FromXmlFile(inc_file)
                dom1 = doc1.documentElement
            except Exception, msg:
                print "WARNING: ", msg

            if dom1 != None:
                includedNode = dom.importNode(dom1, 1)
                doc.appendChild(includedNode)
开发者ID:boris-r-v,项目名称:ArmDsp-Generator,代码行数:33,代码来源:Direction.py


示例9: appendTsXml

    def appendTsXml(self, tsXmlFile):
	os.system("cp "+tsXmlFile+" "+tsXmlFile+".old")
	doc=FromXmlFile(tsXmlFile)
	dom=doc.getElementsByTagName("g").item(0)
	for file in os.listdir(tsXmlFile.replace("/ts.xml","")):
    	    if re.search("impulses\.",file) and re.search("\.xml", file) and not re.search("\.old", file):
		include = doc.createElement("include")
		include.setAttribute("url",file)
	    
		includes = dom.getElementsByTagName("include")
		isAppend = True
		for inc in includes:
		    if inc.getAttribute("url") == file:
			isAppend = False
	    
		if isAppend:
		    dom.appendChild(include)
		    newStr=doc.createTextNode("\n")
		    dom.appendChild(newStr)
		    #Obj.sig(self.out,_("В ts.xml добавлена нода "+str(include)))
		    print _("В ts.xml добавлена нода "+str(include))
		else:
		    #Obj.sig(self.out,_("В ts.xml уже имеется нода <include url='"+file+"' />"))
		    print _("В ts.xml уже имеется нода <include url='"+file+"' />")
	file=open(tsXmlFile,'w')
	Print(doc,file,"utf-8")
	#Obj.sig(self.out,_("Записан файл "+str(tsXmlFile)))
	print "Записан файл ", str(tsXmlFile)
开发者ID:boris-r-v,项目名称:ArmDsp-Generator,代码行数:28,代码来源:generator.py


示例10: appendStoryallXml

    def appendStoryallXml(self, xmlFile, templates_path,result_path):
	os.system("cp "+xmlFile+" "+xmlFile+".old")
        doc=FromXmlFile(xmlFile)
	dom=doc.getElementsByTagName("root").item(0)
	for file in os.listdir(templates_path):
	    if re.search("\.template\.xml",file) and not re.search("impulses\.", file):
	        try:
	            ff = open(result_path+"/"+file.replace(".template",""),'r')
	            ff.close()
	            include = doc.createElement("include")
	            include.setAttribute("url",file.replace(".template",""))
	            includes = dom.getElementsByTagName("include")
	            isAppend = True
	            for inc in includes:
	                if inc.getAttribute("url") == file.replace(".template",""):
	                    isAppend = False
	            if isAppend:
	                dom.appendChild(include)
	                newStr=doc.createTextNode("\n")
		        dom.appendChild(newStr)
		        print "В storyall.xml добавлена нода "+str(include)
		    else:
		        print "В storyall.xml уже имеется нода <include url='"+file.replace(".template","")+"' />"
		except:
		    continue
																																												
	file=open(xmlFile,'w')
	Print(doc,file,"utf-8")
	print "Записан файл ", str(xmlFile)
开发者ID:boris-r-v,项目名称:ArmDsp-Generator,代码行数:29,代码来源:generator.py


示例11: include

    def include(self):

	# Записать эти файлы в storyall.xml
	try:
	    doc = FromXmlFile("storyall.xml")
	    #Print (doc)
	    dom = doc.documentElement

	    inc = doc.createElement("include")
	    inc.setAttribute("url", self.toFile)
	    isIncAlready=False
	    incs = dom.getElementsByTagName("include")
	    for i in incs:
		if i.getAttribute("url")==inc.getAttribute("url"):
		    isIncAlready=True
		    break
	    if not isIncAlready:
		dom.appendChild(inc)
		dom.appendChild(doc.createTextNode("\n"))


	    f=open("storyall.xml", 'w')
	    Print(doc, f, "utf-8")

	except Exception, msg:
	    print "Strelka-Canceler::include(): EXCEPTION (while writing to 'storyall.xml'):", msg
开发者ID:boris-r-v,项目名称:ArmDsp-Generator,代码行数:26,代码来源:canceler.py


示例12: getDomains

def getDomains(targets,release):
  import urllib
  from xml.dom.minidom import parse  
  import xml.dom
  import pickle
  pfamDict ={}
  

  ## Loop through all targets and get pfam domains.
  errors = []
  for target in targets:
    #print "getting Pfam domains for %s" % target
    pfamDict[target] = {}
    pfamDict[target]["domains"] = []
    pfamDict[target]["start"] = []
    pfamDict[target]["end"] = []
    opener = urllib.FancyURLopener({})                                     
    f = opener.open("http://pfam.sanger.ac.uk/protein/%s?output=xml" % target) 
    dom = parse(f)
    if not dom.getElementsByTagName('sequence'):
      #print "encountered Error for %s" %target
      errors.append(target)
      del pfamDict[target]
      continue

    
    for pfam in dom.childNodes:
      if pfam.nodeName == 'pfam':
        for entry in pfam.childNodes:
          if entry.nodeName == 'entry':
            for matches in entry.childNodes:
              if matches.nodeName == 'matches':
                for match in matches.childNodes:
                  if match.nodeName == 'match':
                    if match.getAttribute('type') == 'Pfam-A':
                      pfamDict[target]['domains'].append(match.getAttribute('id'))
                      for location in match.childNodes:
                        if location.nodeName == 'location':
                          start = location.getAttribute('start')
                          end = location.getAttribute('end')
                          pfamDict[target]['start'].append(int(start))
                          pfamDict[target]['end'].append(int(end))
    dom.unlink()
    
    # Add domain count.
    pfamDict[target]['count'] = len(pfamDict[target]['domains'])
    
    # Calculate and add the uniq count of domains. 
    uniqDomains = {}
    for domain in pfamDict[target]['domains']:
      uniqDomains[domain] = 0   
    pfamDict[target]['countUnique'] = len(uniqDomains)
    
  ## Pickle the PfamDict
  output = open('data/protCodPfamDict_%s.pkl' %release, 'w')
  pickle.dump(pfamDict, output)

  print "encountered Error for", errors
  return pfamDict   
开发者ID:MoSander,项目名称:mapChEMBLPfam,代码行数:59,代码来源:getPfamDomains.py


示例13: getNamesArray

    def getNamesArray(self, resultDoc):
	existedNames=[]
	dom=resultDoc.getElementsByTagName("root").item(0)
	objs=dom.getElementsByTagName("obj")
	for obj in objs:
    	    if obj.hasAttribute("name"):
		existedNames.append(obj.getAttribute("name"))
		#print " - "+obj.getAttribute("name")
	return existedNames
开发者ID:boris-r-v,项目名称:ArmDsp-Generator,代码行数:9,代码来源:generator.py


示例14: test_0050_FeatureTags

 def test_0050_FeatureTags(self):
     """Check that features have the correct tags"""
     nodes = dom.getElementsByTagName('feature')
     self.assertEqual(len(nodes), 5)
     nodenames = ['title', 'priority', 'status', 'version', 'risk', 'description', 'relatedrequirements', 'relatedusecases', 'changelist', 'taglist']
     for node in nodes[0].childNodes:
         if node.nodeType == node.TEXT_NODE: continue
         self.failUnless(node.nodeName in nodenames, 'invalid node %s' % node.nodeName)
         nodenames.remove(node.nodeName)
     self.failUnlessEqual(len(nodenames), 0, str(nodenames))
开发者ID:VCTLabs,项目名称:afms,代码行数:10,代码来源:test_afexportxml.py


示例15: test_0060_RequirementTags

 def test_0060_RequirementTags(self):
     """Check that requirements have the correct tags"""
     nodes = dom.getElementsByTagName('requirement')
     self.assertEqual(len(nodes), 17)
     nodenames = ['title', 'priority', 'status', 'version', 'complexity', 'assigned', 'effort', 'category', 'description', 'origin', 'rationale', 'relatedfeatures', 'relatedrequirements', 'relatedusecases', 'relatedtestcases', 'changelist', 'taglist']
     for node in nodes[0].childNodes:
         if node.nodeType == node.TEXT_NODE: continue
         self.failUnless(node.nodeName in nodenames, 'invalid node <%s>' % node.nodeName)
         nodenames.remove(node.nodeName)
     self.failUnlessEqual(len(nodenames), 0, 'missing nodes %s' % str(nodenames))
开发者ID:VCTLabs,项目名称:afms,代码行数:10,代码来源:test_afexportxml.py


示例16: _check_bug_patterns

def _check_bug_patterns(report, patterns):
    try:
        dom = xml.dom.minidom.parseString(patterns)
    except ExpatError:
        return None

    for pattern in dom.getElementsByTagName('pattern'):
        url = _check_bug_pattern(report, pattern)
        if url:
            return url

    return None
开发者ID:YECharles,项目名称:Peach,代码行数:12,代码来源:report.py


示例17: parse_and_store_data

def parse_and_store_data(response, start_date):
    """Parsing XML data from San Francisco's Open311 endpoint and storing it in a postgres database"""

    import xml.dom

    reqs = []

    # Lookup table: use a set since we don't need to associate the the attributes with values
    # May want to add 'updated' flag
    relevant_attrs = {'service_request_id', 'status', 'service_name', 'service_code', 'description',
                        'requested_datetime', 'updated_datetime','expected_datetime', 'address', 'zipcode', 'lat', 'long'}

    try:
        print 'response'
        dom = minidom.parse(response)
    except xml.parsers.expat.ExpatError:
        print 'Expat error'
        append_log('err_log.txt', 'ExpatError. Start date: ' + days[start.weekday()] + ', ' + start.strftime('%Y-%m-%d'))
        return

    for node in dom.getElementsByTagName('request'):
        req_obj = {}

        for attr in node.childNodes:
            if attr.nodeType != xml.dom.Node.ELEMENT_NODE:
                continue
            if attr.childNodes:
                if attr.tagName in relevant_attrs:
                    # http://wiki.postgresql.org/wiki/Introduction_to_VACUUM,_ANALYZE,_EXPLAIN,_and_COUNT // Don't insert null value?
                    req_obj[attr.tagName] = attr.childNodes[0].data or None # will this work?
        # Check if you have a complete set of data for the request
        for relevant_attr in relevant_attrs:
            if relevant_attr not in req_obj:
                req_obj[relevant_attr] = None # To insert null values either omit the field from the insert statement or use None
        
        # Rename the long attribute
        req_obj['lon'] = req_obj['long']
        del req_obj['long']
    
        #print req_obj['zipcode']
        
        if req_obj['zipcode']:
            if not is_number(req_obj['zipcode']):
                req_obj['zipcode'] = None

        if float(req_obj['lat']) > 35 and float(req_obj['lon']) < -121:
            reqs.append(req_obj)

    append_log('log.txt', str(len(reqs)) + ' requests, start date: ' + start.isoformat() + ', ' + str(datetime.datetime.utcnow()) + '\n')
    
    #print 'reqs', reqs
    
    update_database(reqs)
开发者ID:monum,项目名称:311Dashboard,代码行数:53,代码来源:update_postgres_sf.py


示例18: __init__

	def __init__(self, doc):
		"""reads tre structure of the xml document
			doc : a string that contains an xml document"""
		self.doc = doc
		self.modules = []

		dom = parseString(doc)

		root = dom.getElementsByTagName("project")[0]
		for rootMod in root.childNodes:
			r = ModuleFactory.makeModule(rootMod)
			if isinstance(r, Module):
				self.modules.append(r)
开发者ID:leeavital,项目名称:xdocs-py,代码行数:13,代码来源:docs.py


示例19: _ParseDatetimeIntoSecs

  def _ParseDatetimeIntoSecs(dom, tag):
    """Returns the tag body parsed into seconds-since-epoch."""
    el = dom.getElementsByTagName(tag)
    if not el:
      return None
    assert el[0].getAttribute('type') == 'datetime'
    data = el[0].firstChild.data

    # Tracker emits datetime strings in UTC or GMT.
    # The [:-4] strips the timezone indicator
    when = time.strptime(data[:-4], '%Y/%m/%d %H:%M:%S')
    # calendar.timegm treats the tuple as GMT
    return calendar.timegm(when)
开发者ID:aerickson,项目名称:tracker-widget,代码行数:13,代码来源:pytracker.py


示例20: allAntProjectFiles

def allAntProjectFiles() :
	antProjectFiles = []
	for root, dirs, files in os.walk('.'):
		for filename in glob.glob(root + '/build.xml'):
			if len(filename) < 40 and filename.find('test.xml') == -1:
				try :
					dom = parse(filename)
					
					project = dom.getElementsByTagName("project")[0]
					
					if(project is not None):
						antProjectFiles.append(filename)
				except:
					continue
	return antProjectFiles
开发者ID:jason-womack,项目名称:formic,代码行数:15,代码来源:formic.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python dom.unlink函数代码示例发布时间:2022-05-26
下一篇:
Python dom.getDOMImplementation函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap