Python处理XML格式数据的方法详解
作者:jasonblog 发布时间:2021-04-10 22:25:07
本文实例讲述了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()
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具:
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
希望本文所述对大家Python程序设计有所帮助。
猜你喜欢
- CSS对浏览器器的兼容性具有很高的价值,通常情况下IE和Firefox存在很大的解析差异,这里介绍一下兼容要点。常见兼容问题:1、DOCTY
- json 模块Python 提供了内置的 json 模块来处理 JSON 格式的文件。该模块主要分为读取和写入 JSON 文件。读取 JSO
- 写 python 文件时,每个文件开头都必须注明版本和编码。每次我 touch 文件之后粘贴这两句话让我不胜其烦。由于我没有安装 pytho
- 一、测试模型下面这部分来自于某书籍资料,拿过来,按需参考一下:测试模型(1)线性测试1、概念:通过录制或编写对应应用程序的操作步骤产生的线性
- # 2014.10.15 更新了memo.zip, 网盘的exe:修复:1.隔日启动不能正常加载json,加入:1.隐藏任务栏图标,2.通过
- 一、sh是什么SH是一个独特的子进程包装器,可将您的系统程序动态映射到Python函数。SH帮助您用Python编写Shell脚本,既能支持
- Base64是一种用64个字符来表示任意二进制数据的方法。用记事本打开exe、jpg、pdf这些文件时,我们都会看到一大堆乱码,因为二进制文
- 昨天十行代码实现文字识别,感觉怎样,是不是很爽今天咋们继续利用pillow和pytesseract来实现验证码的识别一、环境配置需要 pil
- 以下摘录自 oreilly.JavaScript.The.Definitive.Guide.5th.Edition.Aug.200
- YUV 数据格式概览YUV 的原理是把亮度与色度分离,使用 Y、U、V 分别表示亮度,以及蓝色通道与亮度的差值和红色通道与亮度的差值。其中
- 远程连接oracle只用PLSQLDeveloper客户端,不配置tnsnames.ora文件在PL/SQL中填写:1.UserName:用
- Pandas中的resample,重新采样,是对原样本重新处理的一个方法,是一个对常规时间序列数据重新采样和频率转换的便捷的方法。方法的格式
- 在昨天的文章,《 block 和 inline 的区别是?》里,我给大家留了个问题——LI 元素到底是block level 的,还是 in
- python中eval函数的用法十分的灵活,这里主要介绍一下它的原理和一些使用的场合。下面是从python的官方文档中的解释: &
- Python自带的pdb库,发现用pdb来调试程序还是很方便的,当然了,什么远程调试,多线程之类,pdb是搞不定的。用pdb调试有多种方式可
- python中通过pip安装库文件时出现“EnvironmentError: [WinError 5] 拒绝访问”我遇到的问题:电脑上已经有
- 废话不多说了直接给大家介绍canvas实现手机端用来上传用户头像的代码,具体代码如下所示:<!DOCTYPE html><
- 使用xhtml+css布局经常性地会使用到float,很多邪门的事儿都有可能是浮动在作怪,那么清除浮动就是必须要做的,而且随时性地对父级元素
- yaml 文件的应用场景与格式介绍yaml 文件的应用场景yaml其实也类似于 json、txt ,它们都属于一种文本格式。在我们的实际工作
- 1、流程控制流程控制在编程语言中是最伟大的发明了,因为有了它,你可以通过很简单的流程描述来表达很复杂的逻辑。流程控制包含分三大类:条件判断,