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连接mongodb操作数据示例(mongodb数据库配置类)
Dec 31 Python
python实现每次处理一个字符的三种方法
Oct 09 Python
详细解读Python中的__init__()方法
May 02 Python
python 限制函数调用次数的实例讲解
Apr 21 Python
基于DataFrame改变列类型的方法
Jul 25 Python
python wxpython 实现界面跳转功能
Dec 17 Python
PyTorch的SoftMax交叉熵损失和梯度用法
Jan 15 Python
Python如何访问字符串中的值
Feb 09 Python
python实现翻译word表格小程序
Feb 27 Python
使用python实现时间序列白噪声检验方式
Jun 03 Python
Virtualenv 搭建 Py项目运行环境的教程详解
Jun 22 Python
Python基础之pandas数据合并
Apr 27 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 取得瑞年与平年的天数的代码
2009/08/10 PHP
session在php5.3中的变化 session_is_registered() is deprecated in
2013/11/12 PHP
php自定义的格式化时间示例代码
2013/12/05 PHP
ThinkPHP写数组插入与获取最新插入数据ID实例
2014/11/03 PHP
thinkPHP实现MemCache分布式缓存功能
2016/03/23 PHP
获取页面高度,窗口高度,滚动条高度等参数值getPageSize,getPageScroll
2006/09/22 Javascript
[原创]提供复制本站内容时出现,该文章转自脚本之家等字样的js代码
2007/03/27 Javascript
关于JavaScript中原型继承中的一点思考
2012/07/25 Javascript
javascript unicode与GBK2312(中文)编码转换方法
2013/11/14 Javascript
JS 打印界面的CSS居中代码适用所有浏览器
2014/03/19 Javascript
jQuery实现带水平滑杆的焦点图动画插件
2016/03/08 Javascript
JS脚本加载后执行相应回调函数的操作方法
2018/02/28 Javascript
jquery实现垂直手风琴导航栏
2020/02/18 jQuery
JS实现网页端猜数字小游戏
2020/03/06 Javascript
javascript实现前端成语点击验证优化
2020/06/24 Javascript
vue实现循环滚动列表
2020/06/30 Javascript
[45:46]2014 DOTA2国际邀请赛中国区预选赛5.21 HGT VS DT
2014/05/23 DOTA
[03:16]DOTA2完美大师赛小组赛精彩集锦
2017/11/22 DOTA
[00:33]2018DOTA2亚洲邀请赛TNC出场
2018/04/04 DOTA
[02:43]2018DOTA2亚洲邀请赛主赛事首日TOP5
2018/04/04 DOTA
python3.0 字典key排序
2008/12/24 Python
利用python实现命令行有道词典的方法示例
2017/01/31 Python
手对手的教你用canvas画一个简单的海报的方法示例
2018/12/10 HTML / CSS
美国最古老的精致书写工具制造商:A.T. Cross(高仕)
2018/01/30 全球购物
介绍一下内联、左联、右联
2013/12/31 面试题
机械设计制造专业个人求职信
2013/09/25 职场文书
酒吧总经理岗位职责
2013/12/10 职场文书
党员反对四风问题思想汇报
2014/09/12 职场文书
市委常委班子党的群众路线教育实践活动整改措施
2014/10/02 职场文书
2014教师专业技术工作总结
2014/12/03 职场文书
营销计划书
2015/01/17 职场文书
英文商务邀请函范文
2015/01/31 职场文书
幼儿园教师暑期培训心得体会
2016/01/09 职场文书
初三英语教学反思
2016/02/15 职场文书
这样写python注释让代码更加的优雅
2021/06/02 Python
mysql 乱码 字符集latin1转UTF8
2022/04/19 MySQL