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 调用Java实例详解
Jun 02 Python
python中的计时器timeit的使用方法
Oct 20 Python
python 正确保留多位小数的实例
Jul 16 Python
基于Numpy.convolve使用Python实现滑动平均滤波的思路详解
May 16 Python
win8.1安装Python 2.7版环境图文详解
Jul 01 Python
python中比较两个列表的实例方法
Jul 04 Python
python和c语言的主要区别总结
Jul 07 Python
Python使用matplotlib 模块scatter方法画散点图示例
Sep 27 Python
Python使用jupyter notebook查看ipynb文件过程解析
Jun 02 Python
解决keras GAN训练是loss不发生变化,accuracy一直为0.5的问题
Jul 02 Python
keras分类之二分类实例(Cat and dog)
Jul 09 Python
基于Python爬取京东双十一商品价格曲线
Oct 23 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代码(星期六,星期日总和)
2009/11/12 PHP
php上传图片客户端和服务器端实现方法
2015/03/30 PHP
Laravel与CI框架中截取字符串函数
2016/05/08 PHP
laravel执行php artisan migrate报错的解决方法
2019/10/09 PHP
PHP常用函数之base64图片上传功能详解
2019/10/21 PHP
PHP使用PhpSpreadsheet操作Excel实例详解
2020/03/26 PHP
取选中的radio的值
2010/01/11 Javascript
javascript中用星号表示预录入内容的实现代码
2011/01/08 Javascript
js 浏览器事件介绍
2012/03/30 Javascript
jquery validate 自定义验证方法介绍 日期验证
2014/02/27 Javascript
js实现点击添加一个input节点
2014/12/05 Javascript
解决bootstrap中使用modal加载kindeditor时弹出层文本框不能输入的问题
2017/06/05 Javascript
浅谈vue路径优化之resolve
2017/10/13 Javascript
微信小程序slider组件使用详解
2018/01/31 Javascript
原生JS实现自定义下拉单选选择框功能
2018/10/12 Javascript
详解vue 自定义marquee无缝滚动组件
2019/04/09 Javascript
JS计算两个数组的交集、差集、并集、补集(多种实现方式)
2019/05/21 Javascript
webpack自动打包和热更新的实现方法
2019/06/24 Javascript
element-ui table组件如何使用render属性的实现
2019/11/04 Javascript
Element Backtop回到顶部的具体使用
2020/07/27 Javascript
Python爬取Coursera课程资源的详细过程
2014/11/04 Python
Python正则抓取新闻标题和链接的方法示例
2017/04/24 Python
python利用requests库模拟post请求时json的使用教程
2018/12/07 Python
Django REST framework 分页的实现代码
2019/06/19 Python
python将excel转换为csv的代码方法总结
2019/07/03 Python
容易被忽略的Python内置类型
2020/09/03 Python
百思买加拿大:Best Buy Canada
2018/03/20 全球购物
英国在线汽车和面包车零件商店:Car Parts 4 Less
2018/08/15 全球购物
中软国际Java程序员笔试题
2014/07/19 面试题
电子信息科学专业自荐信
2014/01/30 职场文书
教师节商场活动方案
2014/02/13 职场文书
建筑工程技术专业求职信
2014/07/16 职场文书
爱国影片观后感
2015/06/18 职场文书
python实现调用摄像头并拍照发邮箱
2021/04/27 Python
javascript canvas实现雨滴效果
2021/06/09 Javascript
Tomcat 与 maven 的安装与使用教程
2022/06/16 Servers