python中minidom對xml的常用處理

來源:互聯網
上載者:User
#_*_encoding:utf-8_*_# -- seanyxie  2012.3.23 --# ===minidom操作XML程式碼範例import xmlfrom xml.dom import minidomimport codecs# ==由於minidom預設的writexml()函數在讀取一個xml檔案後,修改後重新寫入如果加了newl='\n',會將原有的xml中寫入多餘的行#  ==因此使用下面這個函數來代替def fixed_writexml(self, writer, indent="", addindent="", newl=""):    # indent = current indentation    # addindent = indentation to add to higher levels    # newl = newline string    writer.write(indent+"<" + self.tagName)    attrs = self._get_attributes()    a_names = attrs.keys()    a_names.sort()    for a_name in a_names:        writer.write(" %s=\"" % a_name)        minidom._write_data(writer, attrs[a_name].value)        writer.write("\"")    if self.childNodes:        if len(self.childNodes) == 1 \          and self.childNodes[0].nodeType == minidom.Node.TEXT_NODE:            writer.write(">")            self.childNodes[0].writexml(writer, "", "", "")            writer.write("</%s>%s" % (self.tagName, newl))            return        writer.write(">%s"%(newl))        for node in self.childNodes:            if node.nodeType is not minidom.Node.TEXT_NODE:                node.writexml(writer,indent+addindent,addindent,newl)        writer.write("%s</%s>%s" % (indent,self.tagName,newl))    else:        writer.write("/>%s"%(newl))minidom.Element.writexml = fixed_writexmldef opXml():    # =====從一個空xml文檔開始    impl = xml.dom.getDOMImplementation()    dom = impl.createDocument(None,'All_Students',None)    root = dom.documentElement    # --建立一個節點,並添加到root下    student = dom.createElement('student')    root.appendChild(student)    # --建立一個子節點,並設定屬性    nameE = dom.createElement('name')    value = u'陳奕迅'    nameE.setAttribute("attr",value)    nameN = dom.createTextNode(value)    nameE.appendChild(nameN)    student.appendChild(nameE)        # -- 寫進檔案,如果出現了unicode,指定檔案的編碼    f = codecs.open('1.xml','w','utf-8')    dom.writexml(f,addindent='  ',newl='\n',encoding = 'utf-8')    f.close()        #=====處理一個已經存在的xml文檔    dom = xml.dom.minidom.parse("1.xml")    root = dom.documentElement    #  -- 重新設定屬性    # --- 返回所有node name為student的節點    allnodes = dom.getElementsByTagName('student')    value = u'王力宏'    for node in allnodes:        node.setAttribute('name',value)    # --刪除節點屬性    for node in allnodes:        node.removeAttribute('name')    # --每個節點有 nodeType,nodeName,和nodeVaulue 等屬性    # --對於textNode,想得到它的常值內容可以使用: .data屬性        print node.nodeType,node.nodeValue    # --也可以刪除節點        root.removeChild(node)    f = codecs.open('1.xml','w','utf-8')    dom.writexml(f,addindent='  ',newl='\n',encoding = 'utf-8')    f.close()if __name__=='__main__':    opXml()

上面的程式碼封裝含了python中minidom操作xml的常用操作

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.