本文实例讲述了Python处理XML格式数据的方法。分享给大家供大家参考,具体如下:
这里的操作是基于Python3平台。
在使用Python处理XML的问题上,首先遇到的是编码问题。
Python并不支持gb2312,所以面对encoding="gb2312"的XML文件会出现错误。Python读取的文件本身的编码也可能导致抛出异常,这种情况下打开文件的时候就需要指定编码。此外就是XML中节点所包含的中文。
我这里呢,处理就比较简单了,只需要修改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文件。
在一个类里面定义call函数可以使得该类可调用,比如下面代码的最后几行,在main函数中。这也很突出地体现了在Python的世界里,一切都是对象,包括对象本身 :)
一直觉得main函数用来测试真是蛮好用的。
#!/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)
最后,就是入口文件,导入上面两个文件,使用xml.dom和os.listdir来递归处理XML文件,并生成一个结果集。
一直觉得Python的UnboundLocalError错误挺有意思的,不知道是不是符号表的覆盖问题。
#!/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转换为utf-8 replaceXmlEncoding(path + '\\' + i) #再提取xml文档中需要的信息 info = extractor(path + '\\' + i) #在上述两行代码没有出现异常的基础上再创建节点 #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()
以上是使用Python处理XML格式数据的方法介绍的详细内容。更多信息请关注PHP中文网其他相关文章!

Python在web开发、数据科学、机器学习、自动化和脚本编写等领域有广泛应用。1)在web开发中,Django和Flask框架简化了开发过程。2)数据科学和机器学习领域,NumPy、Pandas、Scikit-learn和TensorFlow库提供了强大支持。3)自动化和脚本编写方面,Python适用于自动化测试和系统管理等任务。

两小时内可以学到Python的基础知识。1.学习变量和数据类型,2.掌握控制结构如if语句和循环,3.了解函数的定义和使用。这些将帮助你开始编写简单的Python程序。

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

Python3.6环境下加载Pickle文件报错:ModuleNotFoundError:Nomodulenamed...

如何解决jieba分词在景区评论分析中的问题?当我们在进行景区评论分析时,往往会使用jieba分词工具来处理文�...

如何使用正则表达式匹配到第一个闭合标签就停止?在处理HTML或其他标记语言时,常常需要使用正则表达式来�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版
SublimeText3 Linux最新版

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SublimeText3汉化版
中文版,非常好用

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。