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笔记:mysql、redis操作方法
Jun 28 Python
单链表反转python实现代码示例
Feb 08 Python
Python 求数组局部最大值的实例
Nov 26 Python
python 实现批量替换文本中的某部分内容
Dec 13 Python
python判断变量是否为int、字符串、列表、元组、字典的方法详解
Feb 13 Python
python使用html2text库实现从HTML转markdown的方法详解
Feb 21 Python
Selenium之模拟登录铁路12306的示例代码
Jul 31 Python
详解Django中views数据查询使用locals()函数进行优化
Aug 24 Python
Numpy中np.max的用法及np.maximum区别
Nov 27 Python
Python基于Opencv识别两张相似图片
Apr 25 Python
DjangoRestFramework 使用 simpleJWT 登陆认证完整记录
Jun 22 Python
python读取mnist数据集方法案例详解
Sep 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
使用adodb lite解决问题
2006/12/31 PHP
PHP cron中的批处理
2008/09/16 PHP
解析php addslashes()与addclashes()函数的区别和比较
2013/06/24 PHP
PHP的Yii框架中YiiBase入口类的扩展写法示例
2016/03/17 PHP
JS写的数字拼图小游戏代码[学习参考]
2008/10/29 Javascript
jquery应该如何来设置改变按钮input的onclick事件
2012/12/10 Javascript
JS远程获取网页源代码实例
2013/09/05 Javascript
鼠标滑在标题上显示图片的JS代码
2013/11/19 Javascript
jQuery焦点图切换简易插件制作过程全纪录
2014/08/27 Javascript
学习JavaScript设计模式(接口)
2015/11/26 Javascript
Node.js操作mysql数据库增删改查
2016/03/30 Javascript
在Javascript操作JSON对象,增加 删除 修改的简单实现
2016/06/02 Javascript
轻松实现jquery选项卡切换效果
2016/10/10 Javascript
JavaScript实现图片懒加载的方法分析
2018/07/05 Javascript
微信小程序如何实现radio单选框单击打勾和取消
2020/01/21 Javascript
es6中Promise 对象基本功能与用法实例分析
2020/02/23 Javascript
Vue插件之滑动验证码用法详解
2020/04/05 Javascript
vue实现移动端H5数字键盘组件使用详解
2020/08/25 Javascript
[09:34]2018DOTA2国际邀请赛寻真——永不放弃的iG
2018/08/14 DOTA
python奇偶行分开存储实现代码
2018/03/19 Python
TensorFlow利用saver保存和提取参数的实例
2018/07/26 Python
python opencv读mp4视频的实例
2018/12/07 Python
Keras - GPU ID 和显存占用设定步骤
2020/06/22 Python
美国知名日用品连锁超市:Dollar General(多来店)
2017/01/14 全球购物
爱尔兰旅游网站:ebookers.ie
2020/01/24 全球购物
Java和Javasciprt的区别
2012/09/02 面试题
土木工程毕业生推荐信
2013/10/28 职场文书
大学生实习自我鉴定
2013/12/11 职场文书
学生打架检讨书1000字
2014/01/16 职场文书
中学教师请假制度
2014/02/03 职场文书
教师节活动主持词
2014/04/02 职场文书
感恩小明星事迹材料
2014/05/23 职场文书
学校党的群众路线教育实践活动领导班子对照检查材料
2014/09/25 职场文书
2015年环保局工作总结
2015/05/22 职场文书
《岳阳楼记》原文、译文赏析
2019/09/10 职场文书
python双向链表实例详解
2022/05/25 Python