Python處理XML格式數(shù)據(jù)的方法詳解
本文實(shí)例講述了Python處理XML格式數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
這里的操作是基于Python3平臺(tái)。
在使用Python處理XML的問題上,首先遇到的是編碼問題。
Python并不支持gb2312,所以面對(duì)encoding="gb2312"的XML文件會(huì)出現(xiàn)錯(cuò)誤。Python讀取的文件本身的編碼也可能導(dǎo)致拋出異常,這種情況下打開文件的時(shí)候就需要指定編碼。此外就是XML中節(jié)點(diǎn)所包含的中文。
我這里呢,處理就比較簡(jiǎn)單了,只需要修改XML的encoding頭部。
#!/usr/bin/env python import os, sys import re def replaceXmlEncoding(filepath, oldEncoding='gb2312', newEncoding='utf-8'): f = open(filepath, mode='r') content = f.read() content = re.sub(oldEncoding, newEncoding, content) f.close() f = open(filepath, mode='w') f.write(content) f.close() if __name__ == "__main__": replaceXmlEncoding('./ActivateAccount.xml')
接著是使用xml.etree.ElementTree來操作XML文件。
在一個(gè)類里面定義__call__函數(shù)可以使得該類可調(diào)用,比如下面代碼的最后幾行,在__main__函數(shù)中。這也很突出地體現(xiàn)了在Python的世界里,一切都是對(duì)象,包括對(duì)象本身 :)
一直覺得__main__函數(shù)用來測(cè)試真是蠻好用的。
#!/usr/bin/env python import os, re import xml.etree.ElementTree as etree Locale_Path = "./locale.txt" class xmlExtractor(object): def __init__(self): pass def __call__(self, filepath): retDict = {} f = open(filepath, 'r') Line = len(open(filepath, 'r').readlines()) retDict['Line'] = Line tree = etree.parse(f) root = tree.find("ResItem") Id = root.get("ID") retDict['Title'] = Id resItemCnt = len(list(root.findall("ResItem"))) + 1 retDict['ResItemCount'] = resItemCnt retDict['ChineseTip'] = 'None' for child in root: attrDict = child.attrib keyword = "Name" if(keyword in attrDict.keys() and attrDict['Name'] == "Caption"): if len(child.attrib['Value']) > 1: if child.attrib['Value'][0] == '~': title = child.attrib['Value'][1:] else: title = child.attrib['Value'][0:] #print(title) chs = open(Locale_Path).read() pattern = '<String id="' + title + '">[^>]+>' m = re.search(pattern, chs) if m != None: realTitle = re.sub('<[^>]+>', '', m.group(0)) retDict['ChineseTip'] = realTitle f.close() return retDict if __name__ == "__main__": fo = xmlExtractor() d = fo('./ActivateAccount.xml') print(d)
最后,就是入口文件,導(dǎo)入上面兩個(gè)文件,使用xml.dom和os.listdir來遞歸處理XML文件,并生成一個(gè)結(jié)果集。
一直覺得Python的UnboundLocalError錯(cuò)誤挺有意思的,不知道是不是符號(hào)表的覆蓋問題。
#!/usr/bin/env python from xmlExtractor import * from replaceXmlEncoding import * from xml.dom import minidom,Node doc = minidom.Document() extractor = xmlExtractor() totalLines = 0 totalResItemCnt = 0 totalXmlFileCnt = 0 totalErrorCnt = 0 errorFileList = [] xmlRoot = doc.createElement("XmlResourceFile") doc.appendChild(xmlRoot) def myWalkDir(level, path): global doc, extractor, totalLines, totalResItemCnt, totalXmlFileCnt global totalErrorCnt, errorFileList global xmlRoot for i in os.listdir(path): if i[-3:] == 'xml': totalXmlFileCnt += 1 try: #先把xml的encoding由gb2312轉(zhuǎn)換為utf-8 replaceXmlEncoding(path + '\\' + i) #再提取xml文檔中需要的信息 info = extractor(path + '\\' + i) #在上述兩行代碼沒有出現(xiàn)異常的基礎(chǔ)上再創(chuàng)建節(jié)點(diǎn) #print(info) #print(type(i)) xmlNode = doc.createElement("XmlFile") xmlRoot.appendChild(xmlNode) xmlName = doc.createElement("Filename") xmlName.setAttribute('Value', i) #xmlName.appendChild(doc.createTextNode(i)) xmlNode.appendChild(xmlName) filePath = doc.createElement("Filepath") filePath.setAttribute('Value', path[34:]) #filePath.appendChild(doc.createTextNode(path[1:])) xmlNode.appendChild(filePath) titleNode = doc.createElement("Title") titleNode.setAttribute('Value', str(info['Title'])) #titleNode.appendChild(doc.createTextNode(str(info['Title']))) xmlNode.appendChild(titleNode) chsNode = doc.createElement("ChineseTip") chsNode.setAttribute('Value', str(info['ChineseTip'])) #chsNode.appendChild(doc.createTextNode(str(info['Chinese']))) xmlNode.appendChild(chsNode) resItemNode = doc.createElement("ResItemCount") resItemNode.setAttribute('Value', str(info['ResItemCount'])) #resItemNode.appendChild(doc.createTextNode(str(info['ResItemCount']))) xmlNode.appendChild(resItemNode) lineNode = doc.createElement("LineCount") lineNode.setAttribute('Value', str(info['Line'])) #lineNode.appendChild(doc.createTextNode(str(info['Line']))) xmlNode.appendChild(lineNode) descNode = doc.createElement("Description") descNode.setAttribute('Value', '') #descNode.appendChild(doc.createTextNode('')) xmlNode.appendChild(descNode) except Exception as errorDetail: totalErrorCnt += 1 errorFileList.append(path + '\\' + i) print(path + '\\' + i, errorDetail) if os.path.isdir(path + '\\' + i): myWalkDir(level+1, path + '\\' + i) if __name__ == "__main__": path = os.getcwd() + '\\themes' myWalkDir(0, path) print(totalXmlFileCnt, totalErrorCnt) #print(doc.toprettyxml(indent = " ")) resultXml = open("./xmlResourceList.xml", "w") resultXml.write(doc.toprettyxml(indent = " ")) resultXml.close()
PS:這里再為大家提供幾款關(guān)于xml操作的在線工具供大家參考使用:
在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python操作xml數(shù)據(jù)技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Pycharm中SQL語句提示SQL Dialect is Not Config
這篇文章主要介紹了Pycharm中SQL語句提示SQL Dialect is Not Configured的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2022-07-07Python利用wxPython模塊打造ChatGPT式打字效果程序
這篇文章主要為大家介紹了如何利用Python和wxPython模塊打造一個(gè)ChatGPT式打字效果程序,從而增強(qiáng)用戶體驗(yàn)或提高應(yīng)用程序的可讀性,感興趣的可以了解一下2023-05-05python txt中的文件,逐行讀取并且每行賦值給變量問題
這篇文章主要介紹了python txt中的文件,逐行讀取并且每行賦值給變量問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。2023-02-02python如何遍歷指定路徑下所有文件(按按照時(shí)間區(qū)間檢索)
這篇文章主要給大家介紹了關(guān)于python如何遍歷指定路徑下所有文件(按按照時(shí)間區(qū)間檢索)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09Python實(shí)現(xiàn)的下載網(wǎng)頁源碼功能示例
這篇文章主要介紹了Python實(shí)現(xiàn)的下載網(wǎng)頁源碼功能,涉及Python基于http請(qǐng)求與響應(yīng)實(shí)現(xiàn)的網(wǎng)頁源碼讀取功能相關(guān)操作技巧,需要的朋友可以參考下2017-06-06Python增強(qiáng)下git那長(zhǎng)長(zhǎng)的指令詳解
這篇文章主要介紹了Python增強(qiáng)下git那長(zhǎng)長(zhǎng)的指令 ,在開發(fā)中用到的代碼目錄結(jié)構(gòu),本文也給大家詳細(xì)講解,需要的朋友可以參考下2021-09-09M1芯片安裝python3.9.1的實(shí)現(xiàn)
這篇文章主要介紹了M1芯片安裝python3.9.1的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-02-02基于Google的Python編碼規(guī)范標(biāo)準(zhǔn)
這篇文章主要介紹了基于Google的Python編碼規(guī)范標(biāo)準(zhǔn),其中包含了分號(hào),行長(zhǎng)度,括號(hào),縮進(jìn),空行,空格等基本符號(hào)的使用規(guī)則,有需要的朋友可以參考下2021-08-08機(jī)器學(xué)習(xí)Erdos?Renyi隨機(jī)圖生成方法及特性
這篇文章主要為大家介紹了機(jī)器學(xué)習(xí)Erdos?Renyi隨機(jī)圖生成方法及特性詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05