本文实例讲述了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./code/xmljson
在线格式化XML/在线压缩XML:
http://tools./code/xmlformat
XML在线压缩/格式化工具:
http://tools./code/xml_format_compress
XML代码在线格式化美化工具:
http://tools./code/xmlcodeformat
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python操作xml数据技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
# Python
# XML
# 用Python解析XML的几种常见方法的介绍
# Python lxml模块安装教程
# python操作xml文件详细介绍
# 深入解读Python解析XML的几种方式
# 使用PYTHON创建XML文档
# Python 解析XML文件
# 详细解读Python中解析XML数据的方法
# python写入xml文件的方法
# python读取xml文件方法解析
# python操作XML格式文件的一些常见方法
# 递归
# 的是
# 进阶
# 操作技巧
# 相关内容
# 基础上
# 感兴趣
# 这也
# 数据结构
# 给大家
# 只需要
# 先把
# 更多关于
# 转换为
# 所述
# 抛出
# 几款
# 程序设计
# 使用技巧
# 两行
相关文章:
如何在香港服务器上快速搭建免备案网站?
Dapper的Execute方法的返回值是什么意思 Dapper Execute返回值详解
建站之星伪静态规则如何正确配置?
如何快速完成中国万网建站详细流程?
如何在万网开始建站?分步指南解析
如何在Mac上搭建Golang开发环境_使用Homebrew安装和管理Go版本
武汉网站设计制作公司,武汉有哪些比较大的同城网站或论坛,就是里面都是武汉人的?
建站之星2.7模板快速切换与批量管理功能操作指南
建站之星如何快速生成多端适配网站?
如何在Ubuntu系统下快速搭建WordPress个人网站?
如何选择高效响应式自助建站源码系统?
如何在Golang中使用replace替换模块_指定本地或远程路径
如何选择高性价比服务器搭建个人网站?
制作网站软件推荐手机版,如何制作属于自己的手机网站app应用?
h5网站制作工具有哪些,h5页面制作工具有哪些?
网站制作大概要多少钱一个,做一个平台网站大概多少钱?
广州顶尖建站服务:企业官网建设与SEO优化一体化方案
c# 服务器GC和工作站GC的区别和设置
建站之星logo尺寸如何设置最合适?
如何快速启动建站代理加盟业务?
如何零基础开发自助建站系统?完整教程解析
网站制作价目表怎么做,珍爱网婚介费用多少?
建站之星下载版如何获取与安装?
孙琪峥织梦建站教程如何优化数据库安全?
济南企业网站制作公司,济南社保单位网上缴费步骤?
兔展官网 在线制作,怎样制作微信请帖?
建站VPS能否同时实现高效与安全翻墙?
较简单的网站制作软件有哪些,手机版网页制作用什么软件?
seo网站制作优化,网站SEO优化步骤有哪些?
建站之星北京办公室:智能建站系统与小程序生成方案解析
早安海报制作网站推荐大全,企业早安海报怎么每天更换?
公司网站的制作公司,企业网站制作基本流程有哪些?
官网自助建站系统:SEO优化+多语言支持,快速搭建专业网站
天津个人网站制作公司,天津网约车驾驶员从业资格证官网?
品牌网站制作公司有哪些,买正品品牌一般去哪个网站买?
建站之星安装模板失败:服务器环境不兼容?
网站制作多少钱一个,建一个论坛网站大约需要多少钱?
猪八戒网站制作视频,开发一个猪八戒网站,大约需要多少?或者自己请程序员,需要什么程序员,多少程序员能完成?
ppt在线制作免费网站推荐,有什么下载免费的ppt模板网站?
如何在建站主机中优化服务器配置?
营销式网站制作方案,销售哪个网站招聘效果最好?
专业网站建设制作报价,网页设计制作要考什么证?
建站IDE高效指南:快速搭建+SEO优化+自适应模板全解析
如何通过商城免费建站系统源码自定义网站主题?
香港服务器网站卡顿?如何解决网络延迟与负载问题?
佛山网站制作系统,佛山企业变更地址网上办理步骤?
如何有效防御Web建站篡改攻击?
微课制作网站有哪些,微课网怎么进?
购物网站制作公司有哪些,哪个购物网站比较好?
Java解压缩zip - 解压缩多个文件或文件夹实例
*请认真填写需求信息,我们会在24小时内与您取得联系。