使用Python处理XML格式数据的方法介绍
本文实例讲述了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中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

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

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PHP主要是过程式编程,但也支持面向对象编程(OOP);Python支持多种范式,包括OOP、函数式和过程式编程。PHP适合web开发,Python适用于多种应用,如数据分析和机器学习。

PHP适合网页开发和快速原型开发,Python适用于数据科学和机器学习。1.PHP用于动态网页开发,语法简单,适合快速开发。2.Python语法简洁,适用于多领域,库生态系统强大。

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

PHP起源于1994年,由RasmusLerdorf开发,最初用于跟踪网站访问者,逐渐演变为服务器端脚本语言,广泛应用于网页开发。Python由GuidovanRossum于1980年代末开发,1991年首次发布,强调代码可读性和简洁性,适用于科学计算、数据分析等领域。

VS Code 可用于编写 Python,并提供许多功能,使其成为开发 Python 应用程序的理想工具。它允许用户:安装 Python 扩展,以获得代码补全、语法高亮和调试等功能。使用调试器逐步跟踪代码,查找和修复错误。集成 Git,进行版本控制。使用代码格式化工具,保持代码一致性。使用 Linting 工具,提前发现潜在问题。

VS Code 扩展存在恶意风险,例如隐藏恶意代码、利用漏洞、伪装成合法扩展。识别恶意扩展的方法包括:检查发布者、阅读评论、检查代码、谨慎安装。安全措施还包括:安全意识、良好习惯、定期更新和杀毒软件。

在 Notepad 中运行 Python 代码需要安装 Python 可执行文件和 NppExec 插件。安装 Python 并为其添加 PATH 后,在 NppExec 插件中配置命令为“python”、参数为“{CURRENT_DIRECTORY}{FILE_NAME}”,即可在 Notepad 中通过快捷键“F6”运行 Python 代码。

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。
