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解析xml文件实例分享
Dec 04 Python
Python中动态获取对象的属性和方法的教程
Apr 09 Python
Python数据结构之单链表详解
Sep 12 Python
5款非常棒的Python工具
Jan 05 Python
Python将图片转换为字符画的方法
Jun 16 Python
python中实现数组和列表读取一列的方法
Apr 03 Python
Python基于递归和非递归算法求两个数最大公约数、最小公倍数示例
May 21 Python
python pandas修改列属性的方法详解
Jun 09 Python
Python函数基础实例详解【函数嵌套,命名空间,函数对象,闭包函数等】
Mar 30 Python
python在openstreetmap地图上绘制路线图的实现
Jul 11 Python
面向对象学习之pygame坦克大战
Sep 11 Python
Pycharm2020.1安装无法启动问题即设置中文插件的方法
Aug 07 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+DBM的同学录程序(2)
2006/10/09 PHP
探讨如何在php168_cms中提取验证码
2013/06/08 PHP
smarty内置函数config_load用法实例
2015/01/22 PHP
php图像处理函数imagecopyresampled用法详解
2016/12/02 PHP
javascript 静态对象和构造函数的使用和公私问题
2010/03/02 Javascript
javascript学习笔记(十四) window对象使用介绍
2012/06/20 Javascript
jquery中插件实现自动添加用户的具体代码
2013/11/15 Javascript
cookie中的path与domain属性详解
2013/12/18 Javascript
jQuery Masonry瀑布流插件使用详解
2014/11/17 Javascript
Jquery中Event对象属性小结
2015/02/27 Javascript
jQuery mobile 移动web(6)
2015/12/20 Javascript
AngularJS基础 ng-if 指令用法
2016/08/01 Javascript
BootStrapTable服务器分页实例解析
2016/12/20 Javascript
jQuery+ajax的资源回收处理机制分析
2017/01/07 Javascript
js实现添加删除表格(两种方法)
2017/04/27 Javascript
javascript回调函数详解
2018/02/06 Javascript
基于vue循环列表时点击跳转页面的方法
2018/08/31 Javascript
jQuery实现简单的Ajax调用功能示例
2019/02/15 jQuery
原生JS实现图片懒加载之页面性能优化
2019/04/26 Javascript
JavaScript实现公告栏上下滚动效果
2020/03/13 Javascript
如何在JS文件中获取Vue组件
2020/09/16 Javascript
jQuery是用来干什么的 jquery其实就是一个js框架
2021/02/04 jQuery
[02:43]DOTA2英雄基础教程 半人马战行者
2014/01/13 DOTA
TensorFlow实现RNN循环神经网络
2018/02/28 Python
python+mysql实现教务管理系统
2019/02/20 Python
韩国三星旗下的一家超市连锁店:Home Plus
2016/07/30 全球购物
Clearly澳大利亚:购买眼镜、太阳镜和隐形眼镜
2018/04/26 全球购物
全球才华横溢工匠的家居装饰、珠宝和礼物:NOVICA
2021/01/22 全球购物
全球精选男装和家居用品:Article
2020/04/13 全球购物
统计每一学生的平均成绩
2014/06/06 面试题
护理自荐信范文
2013/10/05 职场文书
学校出纳员岗位职责
2014/03/18 职场文书
解除劳动合同协议书范本2014
2014/09/25 职场文书
市场营销计划书
2015/01/17 职场文书
阿里云日志过滤器配置日志服务
2022/04/09 Servers
python pandas 解析(读取、写入)CSV 文件的操作方法
2022/12/24 Python