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的Django框架使用入门指引
Apr 15 Python
如何用Python合并lmdb文件
Jul 02 Python
Python3.5以上版本lxml导入etree报错的解决方案
Jun 26 Python
python字典的常用方法总结
Jul 31 Python
django框架auth模块用法实例详解
Dec 10 Python
python 函数中的参数类型
Feb 11 Python
Django-rest-framework中过滤器的定制实例
Apr 01 Python
python 用opencv实现霍夫线变换
Nov 27 Python
python-opencv 中值滤波{cv2.medianBlur(src, ksize)}的用法
Jun 05 Python
Python中可变和不可变对象的深入讲解
Aug 02 Python
Python 详解通过Scrapy框架实现爬取百度新冠疫情数据流程
Nov 11 Python
Python中 range | np.arange | np.linspace三者的区别
Mar 22 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编写PDF文档生成器
2006/10/09 PHP
Win2003服务器安全加固设置--进一步提高服务器安全性
2007/05/23 PHP
js几个不错的函数 $$()
2006/10/09 Javascript
JavaScript设置FieldSet展开与收缩
2009/05/15 Javascript
jQuery+CSS 半开折叠效果原理及代码(自写)
2013/03/04 Javascript
javascript仿php的print_r函数输出json数据
2013/09/13 Javascript
getJSON调用后台json数据时函数被调用两次的原因猜想
2013/09/29 Javascript
JS获取url链接字符串 location.href
2013/12/23 Javascript
jquery自定义函数的多种方法
2014/01/09 Javascript
js 获取浏览器版本以此来调整CSS的样式
2014/06/03 Javascript
纯JS代码实现气泡效果
2016/05/04 Javascript
angularjs2 ng2 密码隐藏显示的实例代码
2017/08/01 Javascript
Vue函数式组件-你值得拥有
2019/05/09 Javascript
[01:07:21]NAVI vs VG Supermajor 败者组 BO3 第二场 6.5
2018/06/06 DOTA
Python实例之wxpython中Frame使用方法
2014/06/09 Python
python 查找字符串是否存在实例详解
2017/01/20 Python
使用python装饰器计算函数运行时间的实例
2018/04/21 Python
Python实现的IP端口扫描工具类示例
2019/02/15 Python
python实现PID算法及测试的例子
2019/08/08 Python
Python如何将函数值赋给变量
2020/04/28 Python
Python Socket TCP双端聊天功能实现过程详解
2020/06/15 Python
css3媒体查询中device-width和width的区别详解
2020/03/27 HTML / CSS
美国鞋类购物网站:Shiekh Shoes
2016/08/21 全球购物
英国最出名高街品牌:Forever Unique
2018/02/24 全球购物
经典c++面试题五
2014/12/17 面试题
教你打造完美的创业计划书
2014/01/06 职场文书
会计自我鉴定
2014/02/04 职场文书
小学师德标兵先进事迹材料
2014/05/25 职场文书
中华魂放飞梦想演讲稿
2014/08/26 职场文书
意外伤害赔偿协议书范文
2014/09/23 职场文书
2015年幼儿园保育员工作总结
2015/04/23 职场文书
2016年区委书记抓基层党建工作公开承诺书
2016/03/25 职场文书
Nginx优化服务之网页压缩的实现方法
2021/03/31 Servers
Python基础之pandas数据合并
2021/04/27 Python
详解Java ES多节点任务的高效分发与收集实现
2021/06/30 Java/Android
MySQL分区表管理命令汇总
2022/03/21 MySQL