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 制作图片转pdf工具
Jan 30 Python
在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
May 06 Python
Python黑魔法Descriptor描述符的实例解析
Jun 02 Python
Python3 queue队列模块详细介绍
Jan 05 Python
深入分析python数据挖掘 Json结构分析
Apr 21 Python
解决python matplotlib imshow无法显示的问题
May 24 Python
python 获取字符串MD5值方法
May 29 Python
python读取Excel实例详解
Aug 17 Python
使用Python实现在Windows下安装Django
Oct 17 Python
python批量修改图片尺寸,并保存指定路径的实现方法
Jul 04 Python
python误差棒图errorbar()函数实例解析
Feb 11 Python
Python基于staticmethod装饰器标示静态方法
Oct 17 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程序
2006/10/09 PHP
php下使用strpos需要注意 === 运算符
2010/07/17 PHP
处理单名多值表单的详解
2013/06/08 PHP
php实现水仙花数示例分享
2014/04/03 PHP
PHP实现在线阅读PDF文件的方法
2015/06/17 PHP
实例分析PHP中PHPMailer发邮件
2017/12/13 PHP
PHP简单验证码功能机制实例详解
2019/03/27 PHP
js checkbox(复选框) 使用集锦
2009/04/28 Javascript
js 无提示关闭浏览器页面的代码
2010/03/09 Javascript
jQuery maxlength文本字数限制插件
2010/04/16 Javascript
用jquery存取照片的具体实现方法
2013/06/30 Javascript
js为数字添加逗号并格式化数字的代码
2013/08/23 Javascript
js判断字符长度以及中英文数字等
2013/12/31 Javascript
使用jQuery简单实现模拟浏览器搜索功能
2014/12/21 Javascript
浅谈javascript 函数内部属性
2015/01/21 Javascript
一步一步封装自己的HtmlHelper组件BootstrapHelper(三)
2016/09/14 Javascript
Vue2.0 实现移动端图片上传功能
2018/05/30 Javascript
关于node-bindings无法在Electron中使用的解决办法
2018/12/18 Javascript
[01:58]最残酷竞争 2016国际邀请赛中国区预选赛积分循环赛回顾
2016/06/28 DOTA
跟老齐学Python之通过Python连接数据库
2014/10/28 Python
OpenCV实现人脸识别
2017/04/07 Python
python 多个参数不为空校验方法
2019/02/14 Python
Python对接 xray 和微信实现自动告警
2019/09/17 Python
Python数据分析pandas模块用法实例详解
2019/11/20 Python
python可迭代对象去重实例
2020/05/15 Python
加拿大在线旅游公司:Flighthub
2019/03/11 全球购物
what is the difference between ext2 and ext3
2013/11/03 面试题
船舶专业个人求职信范文
2014/01/02 职场文书
农民入党思想汇报
2014/01/03 职场文书
招聘与培训专员岗位职责
2014/01/30 职场文书
领导班子对照检查剖析材料
2014/10/13 职场文书
2015年社区中秋节活动总结
2015/03/23 职场文书
中秋节寄语2015
2015/03/24 职场文书
2019个人工作总结
2019/06/21 职场文书
导游词之安徽巢湖
2019/12/26 职场文书
python实现商品进销存管理系统
2022/05/30 Python