python处理xml文件的方法小结
作者:Flying_tao 发布时间:2023-10-28 01:53:33
标签:python,xml文件
本文实例讲述了python处理xml文件的方法。分享给大家供大家参考,具体如下:
前一段时间因为工作的需要,学习了一点用Python处理xml文件的方法,现在贴出来,供大家参考。
xml文件是按节点一层一层来叠加的,最顶层的是根节点。比如说:
<sys:String x:Key="STR_License_WithoutLicense">Sorry, you are not authorized.</sys:String>
其中sys:String为节点名字,x:Key的内容为Attribute,xml节点值为sys:String的子节点,它是文本节点类型。<节点名称 x:Key="Attribute">子节点。。。
RPD的xml格式:
<ResourceDictionary>
<sys:String x:Key="STR_Startup_LaunchRPD">Launching Polycom RealPresence Desktop</sys:String>
<sys:String x:Key="STR_Startup_CheckFolder">Checking folder</sys:String>
CMAD的xml格式:
<language-strings>
<ABK_CALL comment="verb (command, button on screen to press to place a call);" controls="Button" products="HDX,VSX,CMAD,Venus Main">
<ARABIC notes="" last-change-date="" status="">打电话</ARABIC>
<CHINESE_S notes="" last-change-date="" status="">呼叫</CHINESE_S>
该代码的功能是:
从RPD的String中取出节点值,在CMAD的String中查找是否已经存在,如果存在,则返回CMAD中对应String的NodeName(节点名),并把两个节点名一个做节点名,一个做节点值写到xml文件中;如果不存在,则把RPD中的该节点写到另外一个xml文件中。代码如下:
import xml.dom.minidom
from xml.dom.minidom import Document
RPD_Str_path = "E:/PythonCode/StringResource.en-US.xaml"
RPD_dom = xml.dom.minidom.parse(RPD_Str_path)
CMAD_Str_path = "E:/PythonCode/M500_RPM13_0522.xml"
CMAD_dom = xml.dom.minidom.parse(CMAD_Str_path)
#得到根节点
RPD_root = RPD_dom.documentElement
CMAD_root = CMAD_dom.documentElement
def IsStr_already_Translated(RPD_Str):
for firstLevel in CMAD_root.childNodes:
for SecondLevel in firstLevel.childNodes:
if SecondLevel.nodeType == SecondLevel.ELEMENT_NODE:
if SecondLevel.nodeName == "ENGLISH_US":
if RPD_Str == SecondLevel.childNodes[0].data.strip():
return firstLevel.nodeName
else:
continue
else:
continue
else:
continue
else:
continue
else:
return "Null"
#用Document来写xml文件
Mapping_doc = Document()
Mapping_root = Mapping_doc.createElement("Common_String")
Mapping_doc.appendChild(Mapping_root)
Translation_doc = Document()
Translation_root = Translation_doc.createElement("Need_Translation_String")
Translation_doc.appendChild(Translation_root)
for node in RPD_root.childNodes:
if node.nodeType == node.ELEMENT_NODE:
# print node.getAttribute("x:Key") +" + "+ node.childNodes[0].data
CMAD_Key = IsStr_already_Translated(node.childNodes[0].data.strip())
if(CMAD_Key != "Null"):
mKey = Mapping_doc.createElement(node.getAttribute("x:Key"))
Mapping_root.appendChild(mKey)
mValue = Mapping_doc.createTextNode(CMAD_Key)
mKey.appendChild(mValue)
elif(CMAD_Key == "Null"):
Key = Translation_doc.createElement('sys:String')
Translation_root.appendChild(Key)
Key.setAttribute('x:Key', node.getAttribute("x:Key"))
Value = Translation_doc.createTextNode(node.childNodes[0].nodeValue)
Key.appendChild(Value)
continue
else:
path1 = "E:/PythonCode/ID_Mapping.xml"
try:
import codecs
f1 = codecs.open(path1, "wb", "utf-8")
f1.write(Mapping_doc.toprettyxml(indent=" "))
except:
print('Write xml file failed.... file:{0}'.format(path1))
path2 = "E:/PythonCode/Need_Translate_String.xml"
try:
f2 = codecs.open(path2, "wb", "utf-8")
f2.write(Translation_doc.toprettyxml(indent=" "))
except:
print('Write xml file failed.... file:{0}'.format(path2))
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程序设计有所帮助。


猜你喜欢
- 本文实例讲述了python通过pil将图片转换成黑白效果的方法。分享给大家供大家参考。具体分析如下:pil功能强大,convert方法可以轻
- 经常到这来抄抄改改代码,也贡献一个代码,主要是讨论研究用,没有封装可以进一步改进<!DOCTYPE html PUBLIC "
- “博客就像一本书”这话其实几个月前深圳FB时就有扯到,这也不是什么新概念,也许本身就应该是这样。打个比方,当你拿到一本未看过的书时,理论上你
- 1.方法详情:parametrize(argnames,argvalues,indirect=False,ids=None,scope=No
- 地图 API Map() 构造器实例创建一个 Google 地图:<html><head><scriptsrc
- MySQL有多种存储引擎:MyISAM、InnoDB、MERGE、MEMORY(HEAP)、BDB(BerkeleyDB)、EXAMPLE、
- 一、项目背景:为了回顾关于django的文件上传和分页功能,打算写一个微型的小说网站练练手。花了一个下午的时间,写了个小项目,发现其中其实遇
- 本文介绍了4个asp数据库管理中常用到的access数据库操作程序,一般的网站管理后台都提供了这个功能,方便管理员对数据库数据的管理维护。1
- 技术背景对于一些连续运行或者长时间运行的Python程序而言,如服务器的后端,或者是长时间运行的科学计算程序。当我们涉及到一些中途退出的操作
- 在安装mha4mysql时,大概步骤是:解压,perl Makefile.PL,make, make install。在执行 perl Ma
- 前言:要翻转图像,我们需要使用pygame.transform.flip(Surface, xbool, ybool) 方法,该方法被调用来
- golang中允许对值为 nil 的 slice 添加元素package main func main() { var s []int s
- 找到python3的安装路径python3自带一个把python2代码转换成python3代码的程序,叫"2to3"我们
- 【尊重原创,转载请注明出处】https://blog.csdn.net/guyuealian/article/details/7967225
- 本文实例讲述了JS笛卡尔积算法与多重数组笛卡尔积实现方法。分享给大家供大家参考,具体如下:js 笛卡尔积算法的实现代码,据对象或者数组生成笛
- Golang与python线程详解及简单实例在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是 15*100
- 在布尔索引中,我们将根据 DataFrame 中数据的实际值而不是它们的行/列标签或整数位置来选择数据子集。在布尔索引中,我们使用布尔向量来
- 问题:在Jupyter Notebook中使用args传递参数时出现错误:原始代码:args = parser.parse_args()us
- 平时比较常用的时间、字符串、时间戳之间的互相转换,虽然常用但是几乎每次使用时候都喜欢去搜索一下用法;本文将作为一个笔记,整理一下三者之间的
- 前言9月份,开始开发微信小程序,也曾调研过wepy/mpvue,考虑到后期跨端的需求,最终选择使用了uni-app,本文主要介绍如何使用un