python处理xml文件的方法小结


Posted in Python onMay 02, 2017

本文实例讲述了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))
Python 相关文章推荐
python实现搜索指定目录下文件及文件内搜索指定关键词的方法
Jun 28 Python
Python用Bottle轻量级框架进行Web开发
Jun 08 Python
Django 跨域请求处理的示例代码
May 02 Python
在python中画正态分布图像的实例
Jul 08 Python
django实现模型字段动态choice的操作
Apr 01 Python
python 使用while循环输出*组成的菱形实例
Apr 12 Python
Python 的 __str__ 和 __repr__ 方法对比
Sep 02 Python
用python计算文件的MD5值
Dec 23 Python
python 自动刷新网页的两种方法
Apr 20 Python
Python网络编程之ZeroMQ知识总结
Apr 25 Python
Pytorch可视化的几种实现方法
Jun 10 Python
python模块与C和C++动态库相互调用实现过程示例
Nov 02 Python
python实现的AES双向对称加密解密与用法分析
May 02 #Python
python中安装模块包版本冲突问题的解决
May 02 #Python
Python 操作MySQL详解及实例
Apr 30 #Python
浅谈function(函数)中的动态参数
Apr 30 #Python
python脚本爬取字体文件的实现方法
Apr 29 #Python
Python在图片中添加文字的两种方法
Apr 29 #Python
Python实现对字符串的加密解密方法示例
Apr 29 #Python
You might like
php中smarty实现多模版网站的方法
2015/06/11 PHP
php封装的数据库函数与用法示例【参考thinkPHP】
2016/11/08 PHP
用于table内容排序
2006/07/21 Javascript
PNG背景在不同浏览器下的应用
2009/06/22 Javascript
js 蒙版进度条(结合图片)
2010/03/10 Javascript
jquery星级插件、支持页面中多次使用
2012/03/25 Javascript
javascript中的delete使用详解
2013/04/11 Javascript
JQuery实现点击div以外的位置隐藏该div窗口
2013/09/13 Javascript
jQuery实现默认是闭合的FAQ展开效果菜单
2015/09/14 Javascript
vue router2.0二级路由的简单使用
2017/07/05 Javascript
详解vue axios用post提交的数据格式
2018/08/07 Javascript
微信小程序用户授权、位置授权及获取微信绑定手机号
2019/07/18 Javascript
vue自定义switch开关组件,实现样式可自行更改
2019/11/01 Javascript
Node.js API详解之 os模块用法实例分析
2020/05/06 Javascript
关于vue属性使用和不使用冒号的区别说明
2020/10/22 Javascript
[04:29]DOTA2亚洲邀请赛小组赛第一日 TOP10精彩集锦
2015/02/01 DOTA
python实现在windows服务中新建进程的方法
2015/06/30 Python
Python模拟登录的多种方法(四种)
2018/06/01 Python
使用卷积神经网络(CNN)做人脸识别的示例代码
2020/03/27 Python
快速解决jupyter启动卡死的问题
2020/04/10 Python
利用4行Python代码监测每一行程序的运行时间和空间消耗
2020/04/22 Python
美国经典刺绣和字母儿童服装特卖:Smocked Auctions
2018/07/16 全球购物
环境科学专业大学生自荐信格式
2013/09/21 职场文书
新闻编辑自荐信
2013/11/03 职场文书
医院护士的求职信范文
2013/12/26 职场文书
小学新教师培训方案
2014/02/03 职场文书
《翻越远方的大山》教学反思
2014/04/13 职场文书
解除财产保全担保书
2014/05/20 职场文书
领导班子自我剖析材料
2014/08/16 职场文书
读群众路线的心得体会
2014/09/03 职场文书
教师工作总结范文2014
2014/11/10 职场文书
小学一年级学生评语大全
2014/12/25 职场文书
老公出轨后的保证书
2015/05/08 职场文书
学校标语口号大全
2015/12/26 职场文书
《这片土地是神圣的》教学反思
2016/02/16 职场文书
实现GO语言对数组切片去重
2022/04/20 Golang