Python 解析xml文件的示例


Posted in Python onSeptember 29, 2020

1、获取xml树

import xml.etree.ElementTree as ET


def getTree(xmlName):
  xmlName = xmlName.strip()
  try:
    tree = ET.parse(xmlName)
  except:
    tree = None
    print 'Analysis xml file fail,file name: {}'.format(xmlName)
  return tree

2、获取根节点

def getRoot(tree):
  if tree is not None:
    root = tree.getroot()
  else:
    root = None
    print 'Get root fail'
  return root

3、查看根节点

def seeRoot(root):
  '''<country name="tan">我是小明</country>'''
  if root is not None:
    print 'root tag:', root.tag # 标签(country)
    print 'root attrib:', root.attrib # ?傩裕?ame="tan")
    print 'root text:', root.text # 文本(我是小明)
    print 'root tail:', root.tail # 尾字符串(未涉及)

4、从根开始遍历树

def traverseRoot(root):
  if root is not None:
    for label1 in root:
      print 'label1 tag:', label1.tag
      print 'label1 attrib:', label1.attrib
      print 'label1 text:', label1.text
      print 'label1 tail:', label1.tail
      print '=================='
      for label2 in label1:
        print 'label2 tag:', label2.tag
        print 'label2 attrib:', label2.attrib
        print 'label2 text:', label2.text
        print 'label2 tail:', label2.tail
        print '=================='
        for label3 in label2:
          print 'label3 tag:', label3.tag
          print 'label3 attrib:', label3.attrib
          print 'label3 text:', label3.text
          print 'label3 tail:', label3.tail
          print '=================='

5、找到2012年的gdppc和neighbor下的b标签(找到同层有条件的同层另一个tag的文本)

def findYouNedd(root):
  '''查找year为2012下的b标签的文本'''
  if root is not None:
    for label1 in root:
      for label2 in label1:
        if label1.tag == 'country' and label2.text == '2012': # 找到本层标签为country且下一层有2012文本
          print 'Find tag为country and next year=2012'
          for child in label1:
            if child.tag == 'gdppc':
              print child.text
            for youNeed in child:
              if youNeed.tag == 'b':
                print 'You need:', youNeed.text

6、查找父节点下的子节点

def findChildNode(fatherNode, childNode):
  childNode = childNode.strip()
  if fatherNode is not None:
    childs = fatherNode.findall(childNode)
    print childs
    print len(childs)

7、另一种办法实现第4点

def findYouNedd2(root):
  countryNodes = root.findall('country')
  if root is not None:
    for countryNode in countryNodes:
      if countryNode.find('year').text == '2012':
        print countryNode.find('gdppc').text

8、移除节点

def delNode(tree, nodeName):
  nodeName = nodeName.strip()
  if tree is not None:
    root = tree.getroot()
    findNode = root.find(nodeName)
    if findNode is not None and findNode.tag == nodeName:
      root.remove(findNode)
  tree.write('removeNode.xml') # 移除节点后新的xml

9、xml样例(xmlDemo.xml)

<?xml version="1.0"?>
<data>
  <country name="Liechtenstein">
    <rank>1</rank>
    <year>2008</year>
    <gdppc>141100</gdppc>
    <neighbor name="Austria" direction="E"/>
    <neighbor name="Switzerland" direction="W"/>
  </country>
  <country name="Singapore">
    <rank>4</rank>
    <year>2011</year>
    <gdppc>59900</gdppc>
    <neighbor name="Malaysia" direction="N">123
      <a name="a"> aaa </a>
    </neighbor>
  </country>
  <country name="Singapore">
    <rank>68</rank>
    <year>2012</year>
    <gdppc>13600</gdppc>
    <neighbor name="Costa Rica" direction="W"/>
    <neighbor name="Colombia" direction="E">456
      <b name="b"> bbb </b>
    </neighbor>
  </country>
  <city>789</city>
</data>

以上就是Python 解析xml文件的示例的详细内容,更多关于Python 解析xml的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python3中类、模块、错误与异常、文件的简易教程
Nov 20 Python
python pandas 组内排序、单组排序、标号的实例
Apr 12 Python
python3连接MySQL数据库实例详解
May 24 Python
Python调用adb命令实现对多台设备同时进行reboot的方法
Oct 15 Python
PyCharm在新窗口打开项目的方法
Jan 17 Python
django做form表单的数据验证过程详解
Jul 26 Python
如何基于Python制作有道翻译小工具
Dec 16 Python
详解有关PyCharm安装库失败的问题的解决方法
Feb 02 Python
如何提高python 中for循环的效率
Apr 15 Python
python与c语言的语法有哪些不一样的
Sep 13 Python
Python自动操作神器PyAutoGUI的使用教程
Jun 16 Python
彻底弄懂Python中的回调函数(callback)
Jun 25 Python
Python 字典一个键对应多个值的方法
Sep 29 #Python
python 获取字典特定值对应的键的实现
Sep 29 #Python
Python3 pyecharts生成Html文件柱状图及折线图代码实例
Sep 29 #Python
Python爬取微信小程序通用方法代码实例详解
Sep 29 #Python
详解如何修改python中字典的键和值
Sep 29 #Python
提高python代码运行效率的一些建议
Sep 29 #Python
Python爬取微信小程序Charles实现过程图解
Sep 29 #Python
You might like
基于PHP的cURL快速入门教程 (小偷采集程序)
2011/06/02 PHP
一个显示效果非常不错的PHP错误、异常处理类
2014/03/21 PHP
php判断当前操作系统类型
2015/10/28 PHP
PHP fprintf()函数用法讲解
2019/02/16 PHP
JS中字符问题(二进制/十进制/十六进制及ASCII码之间的转换)
2008/11/03 Javascript
javascript 动态参数判空操作
2008/12/22 Javascript
使用jQuery的将桌面应用程序引入浏览器
2010/11/19 Javascript
js确认删除对话框效果的示例代码
2014/02/20 Javascript
node+express+jade制作简单网站指南
2014/11/26 Javascript
javascript中递归函数用法注意点
2015/07/30 Javascript
Select下拉框模糊查询功能实现代码
2016/07/22 Javascript
jQuery操作cookie
2016/08/08 Javascript
js实现的xml对象转json功能示例
2016/12/24 Javascript
Javascript之图片的延迟加载的实例详解
2017/07/24 Javascript
详解ajax的data参数错误导致页面崩溃
2018/04/30 Javascript
Linux Centos7.2下安装nodejs&amp;npm配置全局路径的教程
2018/05/15 NodeJs
GOJS+VUE实现流程图效果
2018/12/01 Javascript
p5.js实现简单货车运动动画
2019/10/23 Javascript
原生js实现自定义难度的扫雷游戏
2021/01/22 Javascript
[01:54]TI珍贵瞬间系列(三):翻盘
2020/08/28 DOTA
用实例详解Python中的Django框架中prefetch_related()函数对数据库查询的优化
2015/04/01 Python
python 实现红包随机生成算法的简单实例
2017/01/04 Python
python+opencv实现动态物体追踪
2018/01/09 Python
python xlsxwriter库生成图表的应用示例
2018/03/16 Python
Python中最大递归深度值的探讨
2019/03/05 Python
python3获取文件中url内容并下载代码实例
2019/12/27 Python
tensorflow mnist 数据加载实现并画图效果
2020/02/05 Python
python实现人像动漫化的示例代码
2020/05/17 Python
Django怎么在admin后台注册数据库表
2020/11/14 Python
详解HTML5 Canvas绘制不规则图形时的非零环绕原则
2016/03/21 HTML / CSS
如何写自我鉴定
2014/03/19 职场文书
招商引资工作汇报材料
2014/10/28 职场文书
教师先进个人材料
2014/12/17 职场文书
新教师教学工作总结
2015/08/12 职场文书
公司年会主持词范文!
2019/05/07 职场文书
用php如何解决大文件分片上传问题
2021/07/07 PHP