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 相关文章推荐
Python lambda和Python def区别分析
Nov 30 Python
Python素数检测的方法
May 11 Python
Python中操作符重载用法分析
Apr 29 Python
Windows中安装使用Virtualenv来创建独立Python环境
May 31 Python
详解python使用turtle库来画一朵花
Mar 21 Python
python使用pygame模块实现坦克大战游戏
Mar 25 Python
树莓派用python中的OpenCV输出USB摄像头画面
Jun 22 Python
python 魔法函数实例及解析
Sep 25 Python
Python高级property属性用法实例分析
Nov 19 Python
基于FME使用Python过程图解
May 13 Python
python实现取余操作的简单实例
Aug 16 Python
python 爬虫之selenium可视化爬虫的实现
Dec 04 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 获取页面中指定内容的实现类
2014/01/23 PHP
php微信开发之关键词回复功能
2018/06/13 PHP
json数据的列循环示例
2013/09/06 Javascript
js输入框邮箱自动提示功能代码实现
2013/12/10 Javascript
可恶的ie8提示缺少id未定义
2014/03/20 Javascript
JavaScript高级程序设计(第三版)学习笔记1~5章
2016/03/11 Javascript
jQuery中的insertBefore(),insertAfter(),after(),before()区别介绍
2016/09/01 Javascript
js防阻塞加载的实现方法
2016/09/09 Javascript
nodejs中向HTTP响应传送进程的输出
2017/03/19 NodeJs
详解vue模拟加载更多功能(数据追加)
2017/06/23 Javascript
微信小程序自定义导航栏
2018/12/31 Javascript
vue项目中在外部js文件中直接调用vue实例的方法比如说this
2019/04/28 Javascript
JavaScript实现图片的放大缩小及拖拽功能示例
2019/05/14 Javascript
ES6 Symbol数据类型的应用实例分析
2019/06/26 Javascript
[00:27]DOTA2次级职业联赛 - Lilith战队宣传片
2014/12/01 DOTA
python 添加用户设置密码并发邮件给root用户
2016/07/25 Python
django实现用户登陆功能详解
2017/12/11 Python
python编程使用协程并发的优缺点
2018/09/20 Python
Python设计模式之原型模式实例详解
2019/01/18 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
如何解决django-celery启动后迅速关闭
2019/10/16 Python
python通过实例讲解反射机制
2019/10/17 Python
Python pip安装第三方库实现过程解析
2020/07/09 Python
Python hashlib模块的使用示例
2020/10/09 Python
关于Python错误重试方法总结
2021/01/03 Python
python将YUV420P文件转PNG图片格式的两种方法
2021/01/22 Python
html5 Canvas画图教程(5)—canvas里画曲线之arc方法
2013/01/09 HTML / CSS
微软英国官方网站:Microsoft英国
2016/10/15 全球购物
BSTN意大利:德国街头和运动文化高品质商店
2020/12/22 全球购物
开会迟到检讨书
2014/01/08 职场文书
幼儿园教师教学反思
2014/02/06 职场文书
法学专业求职信
2014/07/15 职场文书
部门活动策划方案
2014/08/16 职场文书
四则混合运算教学反思
2016/02/23 职场文书
MySQL锁机制
2021/04/05 MySQL
Java 超详细讲解数据结构中的堆的应用
2022/04/02 Java/Android