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


Python Document.getElementsByTagName方法代码示例

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


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

示例1: createSVG

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
    def createSVG(s, outfile, r = 1):
        src = parse(s.filename)
        new = Document()
        svg = src.getElementsByTagName('svg')[0]
        new.appendChild(svg)
        defs = new.getElementsByTagName('defs')[0]
        #rec0 = new.getElementById(s.rec_name)
        #print (rec0.appendChil)
        
        title = svg.getElementsByTagName('title')[0]
        if 'data-type' in title.attributes and title.attributes['data-type'].value == 'shape':
            s.shapegen(defs, new )
        else:
            s.gen(r, defs, new )
        svg = new.getElementsByTagName('svg')[0]
        #svg.appendChild(rect)
        #svg.setAttribute('width', "1000")
        #svg.setAttribute('height', "1000")
        #use = new.createElement('use')
        #use.setAttribute("xlink:href", "#fractal")
        #use.setAttribute("stroke-width", "4")
        #use.setAttribute("transform", "translate(100,-300) scale(8)")
        #use.setAttribute("stroke", "black")
        #use.setAttribute("stroke-width", "2")
        #svg.appendChild(use)

        with open(outfile, "w") as f:
            new.writexml(f, newl="\n", addindent="    ", indent="    ")
开发者ID:lostfound,项目名称:fractaliar,代码行数:30,代码来源:fractal.py

示例2: UpdateLastSyncDate

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
 def UpdateLastSyncDate(self, LastSyncDate):
     userFile=self.GetUserLastFile(self.GetActualUser())
     if not os.path.exists(userFile):
         doc=Document()
         root = doc.createElement("lastUpdate")
         root.setAttribute( 'datetime', '%s' % LastSyncDate )
         doc.appendChild(root)
     else:
         doc = minidom.parse(userFile)
         root = doc.getElementsByTagName('lastUpdate')[0]
         root.setAttribute( 'datetime', '%s' % LastSyncDate )
         doc.appendChild(root)
     #doc.unlink()
     doc.writexml( open(userFile, 'w'),
                   indent="  ",
                   addindent="  ",
                   newl='\n')
     return LastSyncDate
开发者ID:f4b10,项目名称:X4GA,代码行数:20,代码来源:manager.py

示例3: __init__

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
class XMLcreator:
    # Tworzy nowy document xml
    def __init__(self, fopen=None):
        if(fopen):
            self.doc = parse(str(fopen))
            self.proj_directory = os.path.dirname(os.path.realpath(str(fopen)))
        else:
            self.doc = Document()

    #Metoda sprawdzająca czy dany plik XML jest plikiem opisu projektu
    def isProjectFile(self):
        if self.doc.getElementsByTagName("FloorplanMaker"):
            return True
        else:
            return False

    def getDeviceDescriptor(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]
        des = project.getElementsByTagName("Description_file")[0]

        des_src = des.getAttribute("src")
        return '/'.join([self.proj_directory,des_src])

    def getDeviceVersion(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]
        device = project.getElementsByTagName("Properties")[0]

        return device.getAttribute("model")

    def getEmulationMode(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]
        device = project.getElementsByTagName("Properties")[0]

        return device.getAttribute("mode")

    def getDesignFile(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]
        fl = project.getElementsByTagName("Design_file")[0]

        fl_src = fl.getAttribute("src")
        return '/'.join([self.proj_directory,fl_src])

    def getProjectFile(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]
        fl = project.getElementsByTagName("Project_file")[0]

        fl_src = fl.getAttribute("scr")
        return fl_src

    def getProjectName(self):
        fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0]
        project = fmaker.getElementsByTagName("Project")[0]

        name = project.getAttribute("name")
        return name

    # Metoda tworząca pliku xml projektu
    def createNewProjectFile(self, project_name, project_file_dir, description_file_dir, device, mode):
        FloorplanMaker = self.doc.createElement("FloorplanMaker")
        FloorplanMaker.setAttribute("version","0.1")
        self.doc.appendChild(FloorplanMaker)

        # Tworzenie elementu project
        project = self.doc.createElement("Project")
        project.setAttribute("name", project_name)
        project.setAttribute("author", "Pawel")
        FloorplanMaker.appendChild(project)

        # Tworzenie elementu plik projektu
        fproject = self.doc.createElement("Project_file")
        fproject.setAttribute("src", project_name+'.xml')

        # Tworzenie elementu plik opisu płytki
        fdesign = self.doc.createElement("Description_file")
        fdesign.setAttribute("src", description_file_dir)

        # Tworzenie elementu device
        fproperties = self.doc.createElement("Properties")
        fproperties.setAttribute("model", device)
        fproperties.setAttribute("mode",mode)

        project.appendChild(fproject)
        project.appendChild(fdesign)
        project.appendChild(fproperties)

        # Zapisanie wygenerowanego opisu projektu do pliku
        # --DEBUGER_LINE--
        # print self.doc.toprettyxml(indent="  ")
        plik = open(project_file_dir, "w+")
        self.doc.writexml(plik, indent="\n", addindent="\t")
        plik.close()

    def createSimulationSystemDescription(self, floorplan, oldNcd, newNcd, dir, device, mode):
        board = self.doc.createElement("board")
        board.setAttribute("version","0.1")
#.........这里部分代码省略.........
开发者ID:ComputerArchitectureGroupPWr,项目名称:Floorplan-Maker,代码行数:103,代码来源:XMLCreator.py

示例4: str

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
                    elem.setAttribute("ID", str(id))
                    # elem.setAttribute("Parent", str(parentId))  # visual test only
                    elem.setAttribute("Name", name)

                    # Check
                    if not firstFound:
                        if id == args.identity:
                            # Add element which id is equal with args.identity (only once)
                            root.appendChild(elem)
                            firstFound = True
                    else:
                        if args.identity is None and parentId == 0:
                            root.appendChild(elem)  # direct child of root element

                        # Finding parent of actual element by parentId
                        elementList = doc.getElementsByTagName('Process')
                        for parent in elementList:
                            if parent.getAttribute('ID') == str(parentId):
                                parent.appendChild(elem)
                                break

                # Close connection with CIMOM
                conn.disconnect()

                # Write document, and after unlink it and close output XML file
                doc.writexml(output, addindent="    ", newl='\n')
                doc.unlink()
                output.close()

            except lmiwbem.lmiwbem_core.ConnectionError as connErr:
                print("(ERROR) You cannot connect to " + host)
开发者ID:peterbartha,项目名称:linux-process-list,代码行数:33,代码来源:get_processes.py

示例5: CreateSLF

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
class CreateSLF(TagBase):
    def __init__(self, samples_amount, name, owner, nitrogen_use, dose_rate,
                 external_dose_rate, protocol, reader_id, datecrea):
        self.xml = Document()
        self.slf = self.xml.createElement("SEQ")
        self.xml.appendChild(self.slf)

        self.name = self.xml.createElement("Name")
        self.status = self.xml.createElement("STATUS")
        self.datecrea = self.xml.createElement("Datecrea")
        self.datemod = self.xml.createElement("Datemod")
        self.owner = self.xml.createElement("Owner")
        self.samples_amount = self.xml.createElement("NMuestras")
        self.reader_id = self.xml.createElement("Reader_ID")
        self.nitrogen_use = self.xml.createElement("N2Flow")
        self.dose_rate = self.xml.createElement("Doserate")
        self.external_dose_rate = self.xml.createElement("ExtDoserate")
        self.protocol = self.xml.createElement("Protocol")
        self.seq = self.xml.createElement("seq")

        datemod = datetime.now()
        if (not datecrea) or datecrea is None:
            datecrea = datemod

        self.setTextNode(self.samples_amount, samples_amount)
        self.setTextNode(self.name, name)
        self.setTextNode(self.owner, owner)
        self.setTextNode(self.nitrogen_use, nitrogen_use)
        self.setTextNode(self.dose_rate, dose_rate)
        self.setTextNode(self.external_dose_rate, external_dose_rate)
        self.setTextNode(self.protocol, protocol)
        self.setTextNode(self.reader_id, reader_id)
        self.setTextNode(self.datecrea, datecrea)
        self.setTextNode(self.status, 'pend')
        self.setTextNode(self.datemod, datemod)

        self.slf.appendChild(self.name)
        self.slf.appendChild(self.status)
        self.slf.appendChild(self.datecrea)
        self.slf.appendChild(self.datemod)
        self.slf.appendChild(self.owner)
        self.slf.appendChild(self.samples_amount)
        self.slf.appendChild(self.reader_id)
        self.slf.appendChild(self.nitrogen_use)
        self.slf.appendChild(self.dose_rate)
        self.slf.appendChild(self.external_dose_rate)
        self.slf.appendChild(self.protocol)
        self.slf.appendChild(self.seq)

    def refreshDateMod(self):
        self.datemod.firstChild.data = str(datetime.now())

    def createSample(self, id_):
        self.refreshDateMod()
        samples_ids = self.xml.getElementsByTagName("seq")[0].getElementsByTagName('Sample_ID')
        new_sample = Sample(id_).sample_id
        if len(samples_ids) > 0:
            for sample_id in samples_ids:
                value = sample_id.attributes['sample'].value
                if int(value) == int(id_):
                    return sample_id
                if int(value) > int(id_):
                    self.seq.insertBefore(new_sample, sample_id)
                    return new_sample
        self.seq.appendChild(new_sample)
        return new_sample

    def createProcess(self, id_, parameters, data):
        self.refreshDateMod()
        process = Process(id_, parameters, data).process
        return process

    def createProcessOrder(self, sample_id, id_, type_, status, processes):
        self.refreshDateMod()
        process_order = ProcessOrder(id_, type_, status, processes).process_order
        sample_id.appendChild(process_order)
        return process_order

    def preview(self):
        return self.xml.toprettyxml(indent="    ")

    def save(self, path, rewrite=False):
        if os.path.exists(path):
            if os.path.isfile(path):
                ext = os.path.splitext(path)[-1]
                if ext not in ('.xml', '.slf',):
                    raise ValueError('Incorrect format, must be a slf or xml file.')
                else:
                    if rewrite:
                        try:
                            document = open(path, 'w')
                            self.xml.writexml(document, addindent='    ', newl='\n', encoding='iso-8859-1')
                            return True
                        except:
                            raise ValueError('Error while writing.')
                    return False
            else:
                raise ValueError('Invalid file path.')
        else:
            dirname = os.path.dirname(path)
#.........这里部分代码省略.........
开发者ID:carlos-ferras,项目名称:Sequence-ToolKit,代码行数:103,代码来源:handle_slf.py

示例6: CreateRLF

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
class CreateRLF(TagBase):
    def __init__(self, samples_amount, name, owner, nitrogen_use, dose_rate,
                 external_dose_rate, protocol, status, reader_id, datecrea):
        self.xml = Document()
        self.rlf = self.xml.createElement("rlf")
        self.xml.appendChild(self.rlf)

        self.name = self.xml.createElement("name")
        self.status = self.xml.createElement("status")
        self.datecrea = self.xml.createElement("date_crea")
        self.datemod = self.xml.createElement("date_mod")
        self.owner = self.xml.createElement("owner")
        self.samples_amount = self.xml.createElement("samples_amount")
        self.reader_id = self.xml.createElement("reader_id")
        self.nitrogen_use = self.xml.createElement("N2_flow")
        self.dose_rate = self.xml.createElement("dose_rate")
        self.external_dose_rate = self.xml.createElement("external_dose_rate")
        self.protocol = self.xml.createElement("protocol")
        self.rep = self.xml.createElement("rep")

        datemod = datetime.now()
        if (not datecrea) or datecrea is None:
            datecrea = datemod

        self.setTextNode(self.samples_amount, samples_amount)
        self.setTextNode(self.name, name)
        self.setTextNode(self.owner, owner)
        self.setTextNode(self.nitrogen_use, nitrogen_use)
        self.setTextNode(self.dose_rate, dose_rate)
        self.setTextNode(self.external_dose_rate, external_dose_rate)
        self.setTextNode(self.protocol, protocol)
        self.setTextNode(self.reader_id, reader_id)
        self.setTextNode(self.datecrea, datecrea)
        self.setTextNode(self.status, status)
        self.setTextNode(self.datemod, datemod)

        self.rlf.appendChild(self.name)
        self.rlf.appendChild(self.status)
        self.rlf.appendChild(self.datecrea)
        self.rlf.appendChild(self.datemod)
        self.rlf.appendChild(self.owner)
        self.rlf.appendChild(self.samples_amount)
        self.rlf.appendChild(self.reader_id)
        self.rlf.appendChild(self.nitrogen_use)
        self.rlf.appendChild(self.dose_rate)
        self.rlf.appendChild(self.external_dose_rate)
        self.rlf.appendChild(self.protocol)
        self.rlf.appendChild(self.rep)

    def refreshDateMod(self):
        self.datemod.firstChild.data = str(datetime.now())

    def createSample(self, id_):
        self.refreshDateMod()
        samples_ids = self.xml.getElementsByTagName("rep")[0].getElementsByTagName('sample_id')
        new_sample = Sample(id_).sample_id
        if len(samples_ids) > 0:
            for sample_id in samples_ids:
                value = sample_id.attributes['sample'].value
                if int(value) == int(id_):
                    return sample_id
                if int(value) > int(id_):
                    self.seq.insertBefore(new_sample, sample_id)
                    return new_sample
        self.rep.appendChild(new_sample)
        return new_sample

    def createProcessOrder(self, sample_id, id_, ptype_, dtype_, curves, parameters):
        self.refreshDateMod()
        process_order = ProcessOrder(id_, ptype_, dtype_, curves, parameters).process_order
        sample_id.appendChild(process_order)
        return process_order

    def createCurve(self, number, signal_active, background_active, count_signal, low_signal,
                    high_signal, count_background, low_background, high_background):
        self.refreshDateMod()
        curve = Curve(number, signal_active, background_active, count_signal, low_signal,
                      high_signal, count_background, low_background, high_background).curve
        return curve

    def preview(self):
        return self.xml.toprettyxml(indent="    ")

    def save(self, path, rewrite=False):
        if os.path.exists(path):
            if os.path.isfile(path):
                ext = os.path.splitext(path)[-1]
                if ext not in ('.xml', '.rlf',):
                    raise ValueError('Incorrect format, must be a rlf or xml file.')
                else:
                    if rewrite:
                        try:
                            document = open(path, 'w')
                            self.xml.writexml(document, addindent='    ', newl='\n', encoding='iso-8859-1')
                            return True
                        except:
                            raise ValueError('Error while writing.')
                    return False
            else:
                raise ValueError('Invalid file path.')
#.........这里部分代码省略.........
开发者ID:carlos-ferras,项目名称:Sequence-ToolKit,代码行数:103,代码来源:handle_rlf.py

示例7: CCmdSet

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]

#.........这里部分代码省略.........
        nameTag.appendChild(ptext)

        typeTag = self.doc.createElement("type")
        paramTag.appendChild(typeTag)
        ptext = self.doc.createTextNode("float")
        typeTag.appendChild(ptext)

        valueTag = self.doc.createElement("value")
        paramTag.appendChild(valueTag)
        ptext = self.doc.createTextNode(str(Value))
        valueTag.appendChild(ptext)
        
        self.parse(self.getCmdSet())
        
        
    def printCmdSet(self):
        print self.doc.toprettyxml(indent="  ",encoding="euc-kr")

    def getCmdSet(self):
    	return self.doc.toxml(encoding="euc-kr")
        #print self.doc.toprettyxml(indent="  ",encoding="euc-kr")
        #DataLength = len(self.doc.toxml(encoding="euc-kr"))
        #buffer = struct.pack('I I I %ds'%DataLength, DISCRIMINATOR, VERSION, DataLength,self.doc.toxml())
        #return buffer

    def parse(self,data):
        from xml.dom.minidom import parseString
        global doc
        s = unicode(data,'euc-kr').encode('utf-8')  # euc-kr -> utf-8 
        s = s.replace("encoding=\"euc-kr\"", r"")
 
        doc = parseString(s)

        headerTag = doc.getElementsByTagName('header')[0]
        if headerTag.childNodes.length == 11:

            i=0
            while i < headerTag.childNodes.length:
  
                NodeName = headerTag.childNodes[i].nodeName
                if headerTag.childNodes[i].firstChild != None:
                        NodeValue = headerTag.childNodes[i].firstChild.nodeValue
                else:
                        NodeValue = 'None'

                if NodeName == "ver":
                        ver = NodeValue
                elif NodeName == "cmdname":
                        self.m_cmdname = NodeValue
                elif NodeName == "msgtype":
                        self.m_msgtype = NodeValue 
                elif NodeName == "senderID":
                        self.m_senderID = NodeValue
                elif NodeName == "receiverID":
                        self.m_receiverID = NodeValue
                elif NodeName == "usertag":
                       self.m_usertag = (NodeValue )
                elif NodeName == "status":
                        self.m_status = (NodeValue )
                elif NodeName == "timeout":
                        self.m_timeout = (NodeValue )
                elif NodeName == "contentID":
                        self.m_contentID = NodeValue
                elif NodeName == "cmdID":
                        self.m_cmdID = (NodeValue )
                else:
开发者ID:dattachandan,项目名称:rocon_demos,代码行数:70,代码来源:commandset.py

示例8: __init__

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
class Xml:
    QUERYRESULT = "QueryResult"
    QUERY = "Query"
    RESPONSE = "Response"

    def __init__(self):
        self._doc = Document()
        self._rootNode = self._doc.createElement("Whois")
        self._doc.appendChild(self._rootNode)

    def save(self,name):
        with __builtin__.openany(name, "w") as file:
            loggerxml.debug("saving file %s" % name)
            file.write(self._doc.toxml())

    # Adds a QueryResult node of a
    # specific name to root node.
    # A QueryResult node consists of
    # a Query Node and a Result Node.
    def addQueryResult(self, name, typeOf):
        loggerxml.debug("addQueryResult of name=%s" % (name))

        # look for node with a specific name
        old = self.__lookForQueryResult(name)
        if (old == None):
            request = self._doc.createElement(Xml.QUERYRESULT)
            request.setAttribute("name", name)
            request.setAttribute("type",typeOf)
            self._rootNode.appendChild(request)
        else:
            return old

        return request

    # Searches a queryResult node due
    # to a given name.
    def __lookForQueryResult(self,name):
        old = self._doc.getElementsByTagName(Xml.QUERYRESULT)
        for node in old:
            if name == node.getAttribute("name"):
                return node

        return None

    def __lookForNodeByContent(self, parentNode, tag, content):
        nodes = parentNode.getElementsByTagName(tag)
        for node in nodes:
            if node.childNodes[0].nodeValue == content:
                return node

        return None


    # adds a QueryNode to root
    # it consists of major Query
    # properties and options
    def addQuery(self, parentNode, query=dict()):
        loggerxml.debug("addQuery %s" % str(query))

        # check whether node only needs to
        # be extended
        if parentNode.hasChildNodes():
            queryNode = parentNode.getElementsByTagName(Xml.QUERY)[0]
        else:
            queryNode = self._doc.createElement(Xml.QUERY)
            parentNode.appendChild(queryNode)

        # add child nodes
        queryNode = self.__addDictAsNodes(queryNode, query)

        return parentNode

    # Adds an ResultNode to the document.
    # The function gets a node to
    # add the host and a dictionary.
    def addResponse(self, parentNode, result=dict()):
        loggerxml.debug("addResponse %s" % str(result))

        # look for existing 'response' nodes
        rnodes = parentNode.getElementsByTagName(Xml.RESPONSE)
        if len(rnodes) == 0:
            resultNode = self._doc.createElement(Xml.RESPONSE)
            parentNode.appendChild(resultNode)
        else:
            resultNode = rnodes[0]

        # add child nodes
        resultNode = self.__addDictAsNodes(resultNode, result)

        return parentNode

    # Adds a given dictionary to a node
    # given as parameter. This is relevant
    # for instance for Results and Host nodes.
    # It returns the modified node.
    def __addDictAsNodes(self, parentNode, dictionary=dict()):
        for key in dictionary:
            value = dictionary[key]

            # dictionary
#.........这里部分代码省略.........
开发者ID:yeyintminthuhtut,项目名称:recotak-framework,代码行数:103,代码来源:whoisxml.py

示例9: delphinConstruction

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]

#.........这里部分代码省略.........
        assignment.setAttribute("type", "Material")
        
        reference = self.__constructionFile.createElement("Reference")
        reference.setAttribute("displayName", str_displayName)
        referenceID = self.__constructionFile.createTextNode(str_id)
        reference.appendChild(referenceID)
        assignment.appendChild(reference)
        
        rangeNode = self.__constructionFile.createElement("IBK:Range")
        rangeValue = self.__constructionFile.createTextNode(str(str_order)+" 0 "+str(str_order)+" 0")
        rangeNode.appendChild(rangeValue)
        assignment.appendChild(rangeNode)
        
        return assignment

    # purpose of this function:  This function calls resource requesting java application ResCon
    # submitted variables:       str_resource --> Predefined type definition of implemented resource types
    #                                           defined are: 
    # return values:             True if ressource was created
    #                           False if not
    def __call_ResCon(self, str_sourceURI, str_destinationOfRoot):

        SF_keyWord = "ServiceFramework_Material"
        N_keyWord = "Nandrad_Material"
        targetDir = str_destinationOfRoot
        
        argList = [ "java", "-jar", self.__resConPathAndName, SF_keyWord, str_sourceURI, N_keyWord , targetDir ]
        # check: definition target directory?
        # call ResCon execution process
        try: 
            executionProcess = subprocess.Popen(argList)
            # wait until process is terminated
            timeOut = 1.0 
            while executionProcess.poll() == None:
                time.sleep(timeOut) 
            return True              

        except Exception:
            print("SimulationMatrix: CallResCon: Undefined error while executing ResCon. Check list of arguments: ")
            print(argList)
            return False
        
    def __openCombinationsFile(self, str_source):
        
        materialName = ""
        
        try:
            combinations = os.path.join(os.getcwd(), "combinations.csv")
            fileObject = open(combinations, "r" )
            
        except Exception as e:
        
            print("Error while parsing material file %s." % combinations)
            print e
            return False
            
        else:
            
            for line in fileObject.readlines():
            
                pair = line.split(",")
                source = pair[0]
                destination = pair[1]
                
                #get value string and remove white spaces 
                if( str_source == source ): 
                    
                    pathOfNewMaterial = destination.split(os.sep)
                    
                    if (len(pathOfNewMaterial) > 1):
                        
                        materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1]
                        materialName = materialName.replace("\n","")
                    
                    else:
                        
                        pathOfNewMaterial = destination.split("\\")
                            
                        if (len(pathOfNewMaterial > 1)):
                            
                            materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1]
                            materialName = materialName.replace("\n","")
                        
                        else:
                            
                            pathOfNewMaterial = destination.split("/")
                            materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1]
                            materialName = materialName.replace("\n","")
        
        return materialName
    
    def return_construction(self):
        
        return self.__constructionFile
    
    def add_displayName(self, str_displayName):
        
        displayName = self.__constructionFile.getElementsByTagName("DisplayName")[0]
        displayNameValue = self.__constructionFile.createTextNode(str_displayName)
        displayName.appendChild(displayNameValue)
开发者ID:TUDCIB,项目名称:vl,代码行数:104,代码来源:d6p.py

示例10: __init__

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
class XML_Parser:

    def __init__(self):

        self.charset = sys.getdefaultencoding()

    def init_vars(self):

        for d in self.dic:
            setattr(self, d, self.dic[d])

            self.log.debug('XML Parser: Create variable self.%s needed...' % d)

    def build_xml(self):

        self.init_vars()

        self.doc = Document()

        self.root = self.doc.createElement('info')
        self.doc.appendChild(self.root)

        # create root attributes
        if hasattr(self, 'id'):
            self.root.setAttribute('id', self.id)

        # create child algo
        if hasattr(self, 'algorithm'):
            self.create_node_child('algorithm', self.root, self.algorithm)

        # create child generator
        if hasattr(self, 'generator'):
            self.create_node_child('generator', self.root, self.generator)

        # create childs files
        if hasattr(self, 'files'):
            self.build_array_for_node()

        self.xml = self.doc.toprettyxml(indent = '    ',
            encoding = self.charset)    # pour créer le fichier

    def build_array_for_node(self):

        if 'shortpath' in self.files and self.files['shortpath']:
            array = self.files['shortpath']

        elif 'base' in self.files and self.files['base']:
            array = self.files['base']

        for k, v in array.items():
            child = self.doc.createElement('file')
            self.root.appendChild(child)
            self.create_node_child('name', child, v)
            self.create_node_child('checksum', child, self.files['checksum'][k])
            self.create_node_child('size', child, str(self.files['size'][k]))
            self.create_node_child('date', child, str(self.files['date'][k]))

        del(array)

    def create_node_child(self, element, parent, text):
        child = self.doc.createElement(element)
        parent.appendChild(child)
        txt = self.doc.createTextNode(text.strip())
        child.appendChild(txt)

        # create child attribute
        if element == 'generator' and hasattr(self, 'version'):
            child.setAttribute('version', self.version.strip())


    def get_dict_xml(self):
        if hasattr(self, 'xml'):
            return self.xml
        else:
            return False

    def read_xml(self, doc):

        # comment verifier si fichier XML ?
        if os.path.exists(doc) and os.path.isfile(doc) :

            self.doc = xml.dom.minidom.parse(doc)

            self.xml = dict()

            infos = ['algorithm', 'generator', 'id', 'version']

            for info in infos:
                if info == 'id':
                    self.xml[info] = self.doc.getElementsByTagName('info')[0].getAttribute(info).encode(self.charset)
                elif info == 'version':
                    self.xml[info] = self.doc.getElementsByTagName('generator')[0].getAttribute(info).encode(self.charset)
                else:
                    self.xml[info] = self.doc.getElementsByTagName(info)[0].firstChild.nodeValue.encode(self.charset)

            entries = ['checksum', 'date', 'name', 'size']

            for entry in entries:
                self.xml[entry] = dict()

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

示例11: Document

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
from xml.dom.minidom import Document

doc = Document()

root = doc.createElement('root')
doc.appendChild(root)
main = doc.createElement('Text')
main.setAttribute('id', "1")
root.appendChild(main)

text = doc.createTextNode('Some text here')
main.appendChild(text)

main2 = doc.createElement('Text')
main2.setAttribute('id', "2")
root.appendChild(main2)

l = [e.getAttribute('id') for e in doc.getElementsByTagName('Text')]
print l
print doc.toprettyxml(indent='\t')
开发者ID:GherkinProject,项目名称:GherkinDocs,代码行数:22,代码来源:tools.py

示例12: int

# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import getElementsByTagName [as 别名]
    progress_count = int(sys.argv[2])


log_msg = sys.argv[1]

if os.path.exists(log_filename) == False:
    doc = Document()
    nodePS = doc.createElement("PROGRESS_STATUS")
    nodeP = doc.createElement("PROGRESS")
    txt = doc.createTextNode("0")
    nodeP.appendChild(txt)
    nodePS.appendChild(nodeP)
    doc.appendChild(nodePS)
    with open(log_filename, "w") as f:
        f.write(doc.toxml())

doc = xml.dom.minidom.parse(log_filename)

progress = doc.getElementsByTagName("PROGRESS")
txt = doc.createTextNode(str(int(progress[0].childNodes[0].data) + progress_count))
progress[0].replaceChild(txt, progress[0].childNodes[0])

txt = doc.createTextNode(log_msg)
milestone = doc.createElement("MILESTONE")
milestone.appendChild(txt)

doc.childNodes[0].appendChild(milestone)

with open(log_filename, "w") as f:
    f.write(doc.toxml())
开发者ID:senselab,项目名称:CodeSensor,代码行数:32,代码来源:progress_log.py


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