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 相关文章推荐
JSON Web Tokens的实现原理
Apr 02 Python
Python 实现淘宝秒杀的示例代码
Jan 02 Python
python简易实现任意位数的水仙花实例
Nov 13 Python
详解python中的线程与线程池
May 10 Python
Tensorflow进行多维矩阵的拆分与拼接实例
Feb 07 Python
基于TensorBoard中graph模块图结构分析
Feb 15 Python
Python实现电视里的5毛特效实例代码详解
May 15 Python
13个Pandas实用技巧,助你提高开发效率
Aug 19 Python
Python命令行参数argv和argparse该如何使用
Feb 08 Python
关于Numpy之repeat、tile的用法总结
Jun 02 Python
Python实现PIL图像处理库绘制国际象棋棋盘
Jul 16 Python
python脚本框架webpy模板赋值实现
Nov 20 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 实现301重定向跳转实例代码
2016/07/18 PHP
JS获取月份最后天数、最大天数与某日周数的方法
2015/12/08 Javascript
jQuery中attr()与prop()函数用法实例详解(附用法区别)
2015/12/29 Javascript
js实现table添加行tr、删除行tr、清空行tr的简单实例
2016/10/15 Javascript
easyui messager alert 三秒后自动关闭提示的实例
2016/11/07 Javascript
基于js实现checkbox批量选中操作
2016/11/22 Javascript
EasyUI修改DateBox和DateTimeBox的默认日期格式示例
2017/01/18 Javascript
微信小程序 定位到当前城市实现实例代码
2017/02/23 Javascript
解决JS内存泄露之js对象和dom对象互相引用问题
2017/06/25 Javascript
js基于FileSaver.js 浏览器导出Excel文件的示例
2017/08/15 Javascript
详解一些适用于Node.js的命名约定
2019/12/08 Javascript
[54:30]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
[32:07]完美世界DOTA2联赛PWL S3 LBZS vs Rebirth 第一场 12.16
2020/12/17 DOTA
python3写的简单本地文件上传服务器实例
2018/06/04 Python
一百多行python代码实现抢票助手
2018/09/25 Python
python绘制雪景图
2019/12/16 Python
Pytorch损失函数nn.NLLLoss2d()用法说明
2020/07/07 Python
python批量修改交换机密码的示例
2020/09/22 Python
css3的@media属性实现页面响应式布局示例代码
2014/02/10 HTML / CSS
css3 盒模型以及box-sizing属性全面了解
2016/09/20 HTML / CSS
html5与css3小应用
2013/04/03 HTML / CSS
使用canvas来完成线性渐变和径向渐变的功能的方法示例
2019/07/25 HTML / CSS
美国网上鞋城:Shoeline.com
2016/11/17 全球购物
澳大利亚汽车零部件、音响及配件超市:Automotive Superstore
2018/06/19 全球购物
荣耀俄罗斯官网:HONOR俄罗斯
2020/10/31 全球购物
OLEDBConnection和SQLConnection有什么区别
2013/05/31 面试题
幼儿园教学随笔感言
2014/02/23 职场文书
感恩教育月活动总结
2014/07/07 职场文书
中学生民族团结演讲稿
2014/08/27 职场文书
工作岗位职责范本
2015/02/15 职场文书
自主招生推荐信格式模板
2015/03/24 职场文书
2015年乡镇人大工作总结
2015/04/22 职场文书
入党积极分子培养人意见
2015/06/02 职场文书
导游词之丽江普济寺
2019/10/22 职场文书
Golang 实现超大文件读取的两种方法
2021/04/27 Golang
Rhit高效可视化Nginx日志查看工具
2021/11/01 Servers